/**
 * Created by lbs on 2017/3/9.
 */

app
    .controller('articleCtrl', ['$scope', '$location', '$http', '$timeout',function ($scope, $location, $http,$timeout) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/article/article.html',
                'login.html');
        })
        $('#showPageName').text('查询文章......O(∩_∩)O~~');
     $scope.laydate = function(){
         laydate({elem:"#hello",event:"focus"});
     }


        //var start={
        //    elem:"#start",
        //    format:"YYYY/MM/DD hh:mm:ss",
        //    min:laydate.now(),
        //    max:"2099-06-16 00:00:00",
        //    istime:true,
        //    istoday:false,
        //    choose:function(datas){end.min=datas;end.start=datas}};
        //var end={elem:"#end",format:"YYYY/MM/DD hh:mm:ss",min:laydate.now(),
        //    max:"2099-06-16 00:00:00",istime:true,istoday:false,choose:function(datas){start.max=datas}};laydate(start);laydate(end);


        var currentPage = 1,
            token = localStorage['token'],
            searchCondition = {},
            changeCount = true,
            data = {
                articleId:'',
                title:'',
            };
        searchCondition = data;

        $scope.data = {
            articleId:'',
            title:'',
            start:'',
            editor:'',
            end:'',
            father: '',
            son: '',
            grandson: '',
            status: ''
        };
        //请求数据的方法
        function getList(){
            //获取此时的请求参数
            if(!$scope.data.articleId){
                $scope.data.articleId = 0;
            }
            $scope.data.start = $('#article_date1').val();
            $scope.data.end = $('#article_date2').val();
            $scope.data.father = $('#article_type1 option:selected').text();
            $scope.data.son = $('#article_type2 option:selected').text();
            $scope.data.grandson = $('#article_type3 option:selected').text();
            $scope.data.status = $('#article_status option:selected').val();
            //判断此时和之前的请求条件
            if(compareObj($scope.data,searchCondition)){
                changeCount = false;
            }else{
                changeCount = true;
                currentPage = 1;
                searchCondition = JSON.parse(JSON.stringify($scope.data));
            }
            //进行接口的请求
            $scope.data.num = currentPage;
            $scope.data.size = 20;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/article/select',
                params: $scope.data,
                headers: {'authorization': token},
            }).then(function success(res) {
                res = res.data;
                if (res.result == true) {
                    if(changeCount){
                        layer.msg('共找到'+ res.count+'条记录');
                    }
                    if(changeCount || currentPage ==1){
                        //重置页数显示
                        createPage(20,20,res.count);
                    }
                    $scope.listArr = res.map;
                } else {
                    layer.msg(res.message);
                }
            })
    }
        getList();


        //查询所有
        $scope.articleSelectAll = function () {
            getList();
        }
        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if(i != 'num' && i != 'size'){
                        if ( obj1[i] == obj2[i]) {

                        } else {
                            flag = false;
                        }
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }


        //修改显示或者隐藏
        $scope.articleChange = function (status, id, $scope) {
            if (status == 1) {
                layer.confirm('确定显示吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 0;
                    showOrHide(status, id, $scope);

                }, function(){

                });
            } else {
                layer.confirm('确定隐藏吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 1;
                    showOrHide(status, id, $scope);
                }, function(){

                });
            }
        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/article/insertOrUpdate',
                params: {status: status, articleId: id},
                headers: {'authorization': token},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function success(data) {
                if (data.data.result == true) {
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功');
                } else {
                    jumpLogin(data.data.code);
                }
            })
        }

        //修改按钮
        $scope.articleUpdate = function (articleId) {
            //$location.path('/article/articleAdd');
            sessionStorage.setItem('type', '1');
            sessionStorage.setItem('articleId', articleId);
            var url = window.location.origin+window.location.pathname+'#/article/articleAdd';
            window.open(url);
        }


        getJsonList($scope);
        function getJsonList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }

        $scope.articleAdd = function () {
            $location.path('/article/articleAdd');
            sessionStorage.setItem('type', '0');
        }



        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);  //记录此时的页数
                    getList();
                }
            });
        }
    }])

    //文章新增
    .controller('articleAddCtrl', ['$scope', '$location', '$http', 'postData', '$timeout',function ($scope, $location, $http, postData,$timeout) {

        var type = sessionStorage.getItem('type'),
            articleId = 0,
            token = localStorage['token'];
        if (type == '1') {
            $scope.msg = '修改';
            $scope.showBack = true;
            articleId = sessionStorage.getItem('articleId');
            $('#showPageName').text('修改文章......O(∩_∩)O~~');
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增文章......O(∩_∩)O~~');
        }

        $scope.data = {};
        if (!articleId) {
            articleId = 0;
        } else {
            $http({
                method: 'get',
                url: window.reqUrl+'/management/article/selectOne',
                params: {articleId: articleId},
                headers: {'authorization': token}
            }).then(function success(res) {
                $scope.data.title = res.data.data.title;
                $scope.data.icon = res.data.data.icon;
                $scope.data.authorId = res.data.data.authorId;
                $scope.data.audioTitle = res.data.data.audioTitle;
                $scope.data.audioIcon = res.data.data.audioIcon;
                $scope.data.audioLink = res.data.data.audioLink;
                $scope.data.audioAuthor = res.data.data.audioAuthor;
                $scope.data.weight = res.data.data.weight;

                $('#article_add_type1 option:checked').text(res.data.data.father);
                $('#article_add_type2 option:checked').text(res.data.data.son);
                $('#article_add_type3 option:checked').text(res.data.data.grandson);
                $('#article_add_releaseTime').val(res.data.data.releaseTime);
                $('#editor-trigger').append(res.data.data.summary);
                $("input[name='article_add_status'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }

        $scope.deletePhoto = function(link,type){
                    //第一张图片的删除
                    layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        if(type == 'icon'){
                            $timeout(function(){
                                $scope.data.icon = '';
                            },0);
                        }else{
                            $timeout(function(){
                                $scope.data.audioIcon = '';
                            },0);
                        }
                        layer.msg('删除成功', {icon: 1});
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    }, function(){

                    });

        }

        //提交表单
        $scope.articlePost = function () {
            $scope.data.articleId = articleId;
            $scope.data.summary = $('#editor-trigger').html();
            $scope.data.father = $('#article_add_type1 option:selected').text();
            $scope.data.son = $('#article_add_type2 option:selected').text();
            $scope.data.grandson = $('#article_add_type3 option:selected').text();
            $scope.data.releaseTime = $('#article_add_releaseTime').val();
            $scope.data.status = $('input:radio[name=article_add_status]:checked').val();
            if (!$scope.data.title  || !$scope.data.authorId || !$scope.data.summary  || !$scope.data.father) {
                layer.msg('带红星的字段不能为空!');
                $('.layui-layer-content').css({
                    'background-color':'#393D49',
                    color:'#fff'
                });
                return false;
            }
            //进行提交时，对内容里的图片路径进行处理
            //if($scope.data.summary){
            //    var flag = true;
            //    $.each( $('#editor-trigger img'), function (key, val) {
            //        //获取路径
            //        var src= val.src;
            //        if(src){
            //            //判断是否符合正则表达式
            //            //var arr = src.split('/'),
            //            //    fix = arr[arr.length-1].substr(arr[arr.length-1].length-4),
            //            //    fileName = arr[arr.length-1].substr(0,arr[arr.length-1].length-4);
            //            //var reg = /^\w+$/;
            //            //console.log(fix);
            //            //if(fileName && !reg.test(fileName)){
            //            //    layer.msg('请检查图片名称：以数字、字符、下划线命名!');
            //            //    return false;
            //            //}else{
            //            //    layer.msg('符合命名规范 ');
            //            //}
            //            //判断图片是否存到自己的服务器
            //            console.log(src.indexOf('https://ddup-img1.oss-cn-hangzhou.aliyuncs.com'));
            //            if(src.indexOf('https://ddup-img1.oss-cn-hangzhou.aliyuncs.com') > -1){
            //            }else{
            //                flag = false;
            //               // layer.msg('请检查第'+(key+1)+'张图片的路径，保证图片为直接上传的图片！');
            //                layer.alert('请检查第'+(key+1)+'张图片的路径，保证图片为本地上传！');
            //            }
            //        }
            //
            //    })
            //}
            //if(!flag){
            //    return false;
            //}
            //
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/article/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result && response.result == true) {
                    $('.preserve_btn').attr('disabled', false);
                        if (articleId == 0) {
                            layer.msg('提交成功!');
                            setTimeout(function(){
                                var url = window.location.origin+window.location.pathname+'#/article';
                                window.location.href = url;
                            },1500);
                            $('.layui-layer-content').css({
                                'background-color':'#393D49',
                                color:'#fff'
                            });
                        } else {
                            layer.msg('修改成功');
                            setTimeout(function(){
                               window.close();
                            },1500);
                            $('.layui-layer-content').css({
                                'background-color':'#393D49',
                                color:'#fff'
                            });
                    }
                }
                else {
                    layer.msg(response.data.message);
                }
            }).error(function (response) {
                {
                    layer.msg(response.data.message);
                }
            });
        }

        $scope.articleCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
               if(articleId){
                   window.close();
               }else{
                   var url = window.location.origin+window.location.pathname+'#/article';
                   location.href = url;
               }
            }, function(){

            });
            $('.layui-layer-content').css({
                'background-color':'#393D49',
                color:'#fff'
            });

        }

        $('#article_add_releaseTime').val(getNowFormatDate().replace('T',' '));


        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }

        //上传音频图片和文件
        $('#upload_article_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#upload_radio_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.audioIcon = iconUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#article_add_audio').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            $('#audio_col_file span.course').text('正在上传...');
            client.multipartUpload(storeAs, file).then(function (result) {
                var audioUrl = result.res.requestUrls[0].split('?');
                if (audioUrl.length > 0) {
                    $('.delAudioFile').show();
                    layer.msg('上传成功!');
                }
                $timeout(function(){
                    $scope.data.audioLink = audioUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $scope.del = function () {
            $('#audio_col_icon span').remove();
            $('.del').hide();
            $scope.data.audioIcon = '';
        }
        $scope.delAudioFile = function () {
            //$('.layui-layer-content').css('background','#393D49');
                layer.confirm('确定删除音频吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    layer.msg('删除成功', {icon: 1});
                   $timeout(function(){
                       $scope.data.audioLink = '';
                   },0)
                    console.log($scope.data);
                }, function(){

                });
        }

        //    返回按钮
        $scope.cancel = function () {
          window.close();
        }


    }])


    //视频管理
    .controller('videoCtrl', ['$scope', '$location', '$http','$timeout', function ($scope, $location, $http,$timeout) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/video/video.html',
                'login.html');
        })
        var token = localStorage['token'];
        $('#showPageName').text('查询视频......O(∩_∩)O~~');

        sessionStorage.clear();
        //var common = true; //点了筛选之后要重新开始
        var currentPage = 1,
            searchCondition = {},
            changeCount = true, //重置分页组件
            data = {};
        getListAll(data);

        //条件查询
        $scope.videoSelectAll = function () {
            var videoId = $('#video_id').val();
            var startDate = $('#video_date1').val();
            var endDate = $('#video_date2').val();
            if (videoId == '') {
                videoId = 0;
            }
            var data = {
                videoId: videoId,
                title: $('#video_title').val(),
                start: startDate,
                end: endDate,
                father: $('#video_type1 option:selected').text(),
                son: $('#video_type2 option:selected').text(),
                grandson: $('#video_type3 option:selected').text(),
                editor: $('#founder option:selected').val(),
                status: $('#video_status option:selected').val()
            }
            getListAll(data);
        }
        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        function getListAll(data) {
            if (compareObj(data, searchCondition)) {
                  changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 20;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/video/select',
                params: data,
                headers: {'authorization': token,'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function success(response) {
                if (response.data.result == true) {
                    $scope.currentPage = currentPage;
                    if(changeCount || currentPage ==1){
                        createPage(20, 20, response.data.count);
                       layer.msg('共找到'+ response.data.count+'条记录');
                    }
                    $('.allCount').text('已显示总篇数：' + response.data.count);
                    $scope.listArr = response.data.map;
                } else {
                    layer.msg(response.data.message);
                }
            })
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }


        //修改
        $scope.videoUpdate = function (videoId) {
            //$location.path('/video/videoAdd');
            sessionStorage.setItem('type', '1');
            sessionStorage.setItem('videoId', videoId);
           var url = window.location.origin + window.location.pathname +'#/video/videoAdd';
            window.open(url);
        }

        //修改有效和无效状态
        $scope.videoChange = function (status, id, $scope) {

            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });

        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/video/insertOrUpdate',
                data: {status: status, videoId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'authorization': token,'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function success(data) {
                if (data.data.result == true) {
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功');
                } else {
                    jumpLogin(data.data.code);
                }
            })
        }


        //视频归属
        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }

        $scope.videoAdd = function () {
            $location.path('/video/videoAdd');
            sessionStorage.setItem('type', '0');
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getListAll(searchCondition);
                }
            });
        }


    }])
    //视频管理增加和修改
    .controller('videoAddCtrl', ['$scope', '$location', '$http', 'postData','$timeout', function ($scope, $location, $http, postData,$timeout) {

        var token = localStorage['token'];
        $scope.data = {};
        $scope.data.authorId = '';
        $scope.data.link = '';
        var type = sessionStorage.getItem('type'),
            videoId= '';
        if(type == 0){
            $timeout(function(){
                $scope.msg = '新增';
                $scope.showBack = false;
            },0);
            $('#showPageName').text('新增视频......O(∩_∩)O~~');
        }else{
            videoId = sessionStorage.getItem('videoId');
           $timeout(function(){
               $scope.msg = '修改';
               $scope.showBack = true;
           },0);
            $('#showPageName').text('修改视频......O(∩_∩)O~~');
        }
        if (!videoId) {
            videoId = 0;
            $scope.data = {};
            $('#video_releaseTime').val(getNowFormatDate().replace('T',' '));
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/video/selectOne',
                params: {videoId: videoId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                $scope.data = {
                    title: res.data.data.title,
                    authorId: res.data.data.authorId,
                    summary: res.data.data.summary,
                    releaseTime:res.data.data.releaseTime,
                    link: res.data.data.link,
                    icon:res.data.data.icon,
                    weight: res.data.data.weight
                }
                $('#video_one').val(res.data.data.length.substring(0, 2));
                $('#video_two').val(res.data.data.length.substring(3, 5));
                $('#video_three').val(res.data.data.length.substring(6, 8));
                $('#video_type1 option:checked').text(res.data.data.father);
                $('#video_type2 option:checked').text(res.data.data.son);
                $('#video_type3 option:checked').text(res.data.data.grandson);
                $('#video_releaseTime').val(res.data.data.releaseTime);
                $("input[name='videoAddType'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }

        //提交表单
        $scope.videoPost = function () {
            $scope.data.videoId = videoId;
            $scope.data.length = getVideoLength($('#video_one'), $('#video_two'), $('#video_three'));
            $scope.data.father = $('#video_type1 option:checked').text();
            $scope.data.son = $('#video_type2 option:checked').text();
            $scope.data.grandson = $('#video_type3 option:checked').text();
            $scope.data.releaseTime = $('#video_releaseTime').val();
            $scope.data.status = $('input:radio[name=videoAddType]:checked').val();

            if (!$scope.data.title || !$scope.data.link) {
                //alert('带红星字段不能为空！');
                layer.msg('带红星字段不能为空！');
                return false;
            }
            layer.msg('正在提交中......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/video/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result && response.result == true) {
                            $('.preserve_btn').attr('disabled', true);
                                layer.msg('新增成功');
                                if (videoId == 0) {
                                    setTimeout(function(){
                                        var url = window.location.origin + window.location.pathname +'#/video';
                                        window.location.href = url;
                                    },1500);
                                } else {
                                     layer.msg('修改成功');
                                         setTimeout(function(){
                                             window.close();
                                         },1500);
                                }
                        }
                        else {
                            layer.msg(response.data.message);
                        }
            }).error(function (response) {
                {
                   layer.msg(response.data.message);
                }
            });
        }

        //图片上传
        $('#upload_video_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
               $timeout(function(){
                  layer.msg('上传成功');
                   $scope.data.icon = iconUrl[0].replace('http', 'https');
               },0)

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $scope.showPhotos = function(link){
            //第一张图片的删除
            layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                $timeout(function(){
                    $scope.data.icon = '';
                },0);
                layer.msg('删除成功', {icon: 1});
            }, function(){

            });

        }

        var type = sessionStorage.getItem('type');
        if (type) {
            $scope.msg = '修改'
            $scope.showBack = true;
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
        }


        $scope.videoCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                if(videoId){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/video';
                    location.href = url;
                    layer.msg('返回');
                }
            }, function(){

            });
            $('.layui-layer-content').css('background-color','#393D49');
        }


        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }

        $scope.cancel = function () {
            //$location.path('/video');
            $('.left .modal').remove();
            window.close();
        }
    }])



    //广告图管理
    .controller('adImgCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/ad/ad_img.html',
                'login.html');
        })
        $('#showPageName').text('查询广告图......O(∩_∩)O~~');
        var token = localStorage['token'];
        sessionStorage.clear();
        var currentPage = 1,
            data = {size: 1000, num: currentPage},
            searchCondition = data;
        var changeCount = true;
        getAllList(data);
        $scope.adImgSelectAll = function () {
            var bannerId = $('#ad_img_id').val();
            if (bannerId == '') {
                bannerId = 0;
            }
            var data = {
                bannerId: bannerId,
                mold: $('#ad_radio_name option:checked').val(),
                status: $('#ad_status option:checked').val()
            }

            getAllList(data);
        }
        function getAllList(data) {
            if (compareObj(data, searchCondition)) {
                changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 1000;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/banner/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization': token}
            }).then(function success(response) {

                if (response.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = 1;
                    if(changeCount || currentPage ==1){
                        //createPage(20, 20, response.data.count);
                        createPage(1000, 20, response.data.map.length);
                        layer.msg('查询到'+response.data.map.length+'条记录');
                    }
                    $.each(response.data.map, function (key, val) {
                        switch (val.mold) {
                            case 0:
                                val.molds = '大首页幻灯';
                                break;
                            case 1:
                                val.molds = '活动页幻灯';
                                break;
                            case 2:
                                val.molds = '番剧幻灯';
                                break;
                            case 3:
                                val.molds = '游戏幻灯';
                                break;
                            case 4:
                                val.molds = '手办幻灯';
                                break;
                            case 5:
                                val.molds = 'cos幻灯';
                                break;
                            case 6:
                                val.molds = '舞蹈幻灯';
                                break;
                            case 7:
                                val.molds = '音乐幻灯';
                                break;
                            case 8:
                                val.molds = '御宅♂幻灯';
                                break;
                            case 9:
                                val.molds = '彼女♀幻灯';
                                break;
                            case 10:
                                val.molds = '美物幻灯';
                                break;
                        }
                    })
                    $scope.listArr = response.data.map;
                } else {
                    layer.msg(response.data.message);
                }
            })
        }

        $scope.change = function (status) {
            if (status == '0') {
                return '隐藏';
            } else {
                return '显示';
            }
        }
        $scope.picChange = function (status) {
            if (status == '0') {
                return '有效';
            } else {
                return '无效';
            }
        }

        //修改有效和无效状态
        $scope.adImgChange = function (status, id, $scope) {
            //更改状态
            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });
        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/banner/insertOrUpdate',
                data: {status: status, bannerId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization': token}
                //headers: {'authorization': token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    //$scope.listArr.splice($scope.$index, 1);
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功');
                } else {
                    //jumpLogin(data.data.code);
                    layer.msg(response.data.message);
                }
            })
        }

        $scope.updateAdImg = function (bannerId) {
            sessionStorage.setItem('bannerId', bannerId);
            sessionStorage.setItem('type', '1');
            //$location.path('/ad/adImgAdd');
            var url = window.location.origin+window.location.pathname+'#/ad/adImgAdd';
            window.open(url);
        }

        $scope.adImgAdd = function () {
            sessionStorage.setItem('type', '0');
            $location.path('/ad/adImgAdd');
        }
        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getListAll(searchCondition);
                }
            });
        }

    }])
    .controller('adImgAddCtrl', ['$scope', '$location', '$http', 'postData','$timeout', function ($scope, $location, $http, postData,$timeout) {
        $scope.dataAll = {
            title:''
        };
        var type = sessionStorage.getItem('type'),
            token = localStorage['token'],
             bannerId = '';
        if (type == 0) {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#adImg_releaseTime').val(getNowFormatDate().replace('T',' '))
            $('#showPageName').text('新增广告图......O(∩_∩)O~~');
            bannerId = 0;
        } else {
            $scope.msg = '修改';
            $scope.showBack = true;
            $('#showPageName').text('修改广告图......O(∩_∩)O~~');
            bannerId   = sessionStorage.getItem('bannerId') || 0;
        }


        if (!bannerId) {
            $scope.dataAll = {};
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/banner/selectOne',
                params: {bannerId: bannerId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                $scope.dataAll = {
                    link: res.data.data.link,
                    title: res.data.data.title,
                    weight: res.data.data.weight,
                    releaseTime:res.data.data.releaseTime,
                    icon:res.data.data.icon
                }

                $('#adImg_add_mold option[value="' + res.data.data.mold + '"]').attr('selected', 'selected');
                $('#adImg_releaseTime').val(res.data.data.releaseTime)
                $("input[name='mold_type'][value='" + res.data.data.type + "']").attr('checked', true);
                $("input[name='addType'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }

        //提交表单
        $scope.adImgPost = function () {
            $scope.dataAll.bannerId = bannerId;
            $scope.dataAll.mold = parseInt($('#adImg_add_mold option:checked').val());
            $scope.dataAll.type = parseInt($('input:radio[name=mold_type]:checked').val());
            $scope.dataAll.releaseTime = $('#adImg_releaseTime').val();
            $scope.dataAll.status = $('input:radio[name=addType]:checked').val();
            if ($scope.dataAll.releaseTime == '') {
                layer.msg('带红星字段不能为空！');
                return false;
            }
            if(!$scope.dataAll.title){
                layer.msg('请填写广告标题！');
                return;
            }
            if($scope.dataAll.type == 0 || $scope.dataAll.type == 1 || $scope.dataAll.type == 2){
                if($scope.dataAll.link){
                    if(parseInt($scope.dataAll.link) >= 0){
                        console.log('符合规则 ');
                    }else{
                        layer.msg('请填写合适的链接！');
                        return;
                    }
                }
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/banner/insertOrUpdate',
                data: $scope.dataAll,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    $('.preserve_btn').attr('disabled', true);
                    if (bannerId == 0) {
                        layer.msg('提交成功');
                        //$location.path('/ad/adImg');
                        var url = window.location.origin+window.location.pathname+'#/ad/adImg';
                        location.href = url;
                        layer.msg('返回成功');
                    } else {
                        layer.msg('修改成功');
                           setTimeout(function(){
                               window.close();
                           },2000);
                    }
                }
            }).error(function (data) {

            });
        }

        $scope.showPhotos = function(link){
            //第一张图片的删除
            layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                    $timeout(function(){
                        $scope.dataAll.icon = '';
                    },0);
                layer.msg('删除成功', {icon: 1});
            }, function(){

            });

        }

        //图片上传
        $('#upload_adImg_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.dataAll.icon = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });


        $scope.adImgCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                if(bannerId){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/ad/adImg';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });
        }

        $scope.cancel = function(){
            window.close();
        }
    }])

    //广播台管理
    .controller('adAudioCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/ad/ad_img.html',
                'login.html');
        })
        sessionStorage.clear();
        $('#showPageName').text('查询广播台......O(∩_∩)O~~');
        var currentPage = 1,
            data = {size: 1000, num: currentPage},
            token = localStorage['token'],
            searchCondition = data;
        var changeCount = true;
        getAllList(data);
        $scope.adAudioSelectAll = function () {
            var playId = $('#ad_audio_id').val();
            if (playId == '') {
                playId = 0;
            }

            var data = {
                playId: playId,
                title: $('#ad_radio_name').val(),
            }
            if (playId == '' && $('#ad_radio_name').val() == '') {
                data = '';
            }
            getAllList(data);
        }
        function getAllList(data) {
            if (compareObj(data, searchCondition)) {
                changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 1000;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/play/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(response) {
                if (response.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = 1;  //该接口暂时没有返回一共多少条数据
                    if(changeCount || currentPage ==1){
                        //createPage(20, 20, response.data.count);
                        createPage(1000, 20, response.data.map.length);
                        layer.msg('查询到'+response.data.map.length+'条记录');
                    }
                    $scope.listArr = response.data.map;
                } else {
                    layer.msg(response.data.message);
                }
            })
        }


        //删除
        $scope.adAudioDelete = function (id, $scope) {
            layer.confirm('确定要删除吗？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                $http({
                    method: 'GET',
                    url: window.reqUrl+'/management/play/delete',
                    params: {playId: id},
                    transformRequest: function (obj) {
                        var str = [];
                        for (var p in obj) {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
                }).then(function success(data) {
                    if (data.data.result == true) {
                        layer.msg('删除成功', {icon: 1});
                        $scope.listArr.splice($scope.$index, 1);
                    } else {
                        //jumpLogin(data.data.code);
                        layer.msg(data.data.message);
                    }
                })
            }, function(){
                //layer.msg('也可以这样', {
                //    time: 20000, //20s后自动关闭
                //    btn: ['明白了', '知道了']
                //});
            });
        }
        /**
         * 修改
         * @param id
         */
        $scope.audioUpdate = function (id) {
            $location.path('/ad/adAudioAdd');
            sessionStorage.setItem('audioType', 1);
            sessionStorage.setItem('audioId', id);
        }

        $scope.adAudioAdd = function () {
            sessionStorage.setItem('audioType', 0);
            $location.path('/ad/adAudioAdd');
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }
        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }
    }])
    .controller('adAudioAddCtrl', ['$scope', '$location', '$http', 'postData','$timeout', function ($scope, $location, $http, postData,$timeout) {
        $('#showPageName').text('新增广播图......O(∩_∩)O~~');
        var type = sessionStorage.getItem('audioType'),
            token = localStorage['token'];
        if (type == 0) {
            $scope.msg = '新增'
        } else {
            $scope.msg = '修改'
        }

        var audioId = sessionStorage.getItem('audioId');
        //获取该信息
        $scope.data = {
            releaseTime:getNowFormatDate().replace('T', ' '),
            title:'',
            icon:'',
            link:''
        };


        $scope.adAudioPost = function () {
            $scope.data.playId = 0;
            $scope.data.status = '0';
            if (!$scope.data.title) {
                layer.msg('带红星字段不能为空!');
                return false;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/play/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    $('.preserve_btn').attr('disabled', true);
                    layer.msg('提交成功');
                    setTimeout(function(){
                        var url = window.location.origin + window.location.pathname + '#/ad/adAudio';
                        window.location.href = url;
                    },1500);
                }
            }).error(function (data) {

            });


        }
        // 删除
        $scope.delete = function(link,type){
            switch(type){
                case 'icon':
                    layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        $timeout(function(){
                            $scope.data.icon = '';
                        },0);
                        layer.msg('删除成功', {icon: 1});
                    }, function(){

                    });
                    break;
                case 'audio':
                    layer.confirm('确定删除音频吗', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        $timeout(function(){
                            $scope.data.link = '';
                        },0);
                        layer.msg('删除成功', {icon: 1});
                    }, function(){

                    });
                    break;
            }

        }

        //上传音频图片和文件
        $('#upload_adAudio_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#adAudio_add_audio').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            $('#adAudio_col_file span').text('正在上传...');
            client.multipartUpload(storeAs, file).then(function (result) {
                var audioUrl = result.res.requestUrls[0].split('?');
                if (audioUrl.length > 0) {
                    layer.msg('上传成功');
                }
               $timeout(function(){
                   $scope.data.link = audioUrl[0].replace('http', 'https');
               },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $scope.adAudioCancel = function () {
            //if (confirm('请确保提交成功，返回之后数据会清空，确定返回吗？')) {
            //    $location.path('/ad/adAudio');
            //    $('.left .modal').remove();
            //}
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //if(bannerId){
                //    window.close();
                //}else{
                    var url = window.location.origin+window.location.pathname+'#/ad/adAudio';
                    location.href = url;
                    layer.msg('返回成功');
                //}
            }, function(){

            });
        }

        $scope.cancel = function () {
            $location.path('/ad/adAudio');
            $('.left .modal').remove();
        }
    }])

    //资源主推管理
    .controller('adResourceCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/ad/resource.html',
                'login.html');
        })
        $('#showPageName').text('查询资源主推......O(∩_∩)O~~');
        //sessionStorage.clear();
        var currentPage = 1,
            changeCount = true,
            token = localStorage['token'],
            searchCondition = {};
        var data = {};
        searchCondition = data;
        getAllList(data);
        $scope.pushSelectAll = function () {
            var pushId = $('#ad_pushId').val();
            if (pushId == '') {
                pushId = 0;
            }
            var data = {
                pushId: pushId,
                type: $('#push_type option:checked').val(),
                mm: $('#push_tag option:checked').val(),
                status: $('#push_status option:checked').val(),
            }
            getAllList(data);
        }
        function getAllList(data) {
            if (compareObj(data, searchCondition)) {
                changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 20;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/push/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(response) {
                if (response.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = 1; //该接口暂时没有返回总条数
                    if(changeCount || currentPage ==1){
                        createPage(20, 20, response.data.count);
                        layer.msg('查询到'+response.data.count+'条记录');
                    }
                    $scope.list = response.data.map;
                } else {
                    layer.msg(response.data.message);
                }
            })
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        $scope.pushChange = function (status, id, $scope) {
            if (status == 1) {
                layer.confirm('确定显示吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 0;
                    showOrHide(status, id, $scope);

                }, function(){

                });
            } else {
                layer.confirm('确定隐藏吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 1;
                    showOrHide(status, id, $scope);
                }, function(){

                });
            }
        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/push/insertOrUpdate',
                data: {status: status, pushId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    //$scope.list.splice($scope.$index, 1);
                    if($scope.list[$scope.$index].status == 0){
                        $scope.list[$scope.$index].status = 1;
                    }else{
                        $scope.list[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功');
                } else {
                    jumpLogin(data.data.code);
                }
            })
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }

        $scope.pushAdd = function () {
            $location.path('/ad/resourceAdd');
            sessionStorage.setItem('type', '0');
        }

        //修改按钮
        $scope.pushUpdate = function (pushId) {
            //$location.path('/ad/resourceAdd');
            sessionStorage.setItem('type', '1');
            sessionStorage.setItem('pushId', pushId);
            var url = window.location.origin+window.location.pathname+'#/ad/resourceAdd';
            window.open(url);
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }

    }])
    .controller('adResourceAddCtrl', ['$scope', '$location', '$http', 'postData', function ($scope, $location, $http, postData) {
        var type = sessionStorage.getItem('type'),
            token = localStorage['token'],
            pushId = '';
        if (type == '1') {
            $scope.msg = '修改';
            $scope.showBack = true;
            $('#showPageName').text('修改资源主推......O(∩_∩)O~~');
            pushId = sessionStorage.getItem('pushId');
        } else {
            $scope.showBack = false;
            $('#showPageName').text('新增资源主推......O(∩_∩)O~~');
            pushId = 0;
        }

        if(pushId == 0){
            $scope.data = {
                start:'',
                end:'',
                first:'',
                last:''
            };
        }else{
            console.log('此时的pushId'+pushId);
            //sessionStorage.clear();
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/push/selectOne',
                params: {pushId: pushId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                $scope.data = res.data.data;

                $("input[name='type'][value='" + res.data.data.type + "']").attr('checked', true);

                $("#push_major option[value='" + res.data.data.major + "']").attr('selected', 'selected');
                if(res.data.data.start && res.data.data.start.length<=10){
                    res.data.data.start = res.data.data.start +' 00:00:00';
                }
                if(res.data.data.end && res.data.data.end.length<=10){
                    res.data.data.end = res.data.data.end +' 00:00:00';
                }
                if(res.data.data.first && res.data.data.first.length<=10){
                    res.data.data.first = res.data.data.first +' 00:00:00';
                }
                if(res.data.data.last && res.data.data.last.length<=10){
                    res.data.data.last = res.data.data.last +' 00:00:00';
                }
                $('#push_major_time1').val(res.data.data.start);
                $('#push_major_time2').val(res.data.data.end);
                $("#push_minor option[value='" + res.data.data.minor + "']").attr('selected', 'selected');
                $('#push_minor_time1').val(res.data.data.first);
                $('#push_minor_time2').val(res.data.data.last);

                //$('#push_tag option:checked').text(res.data.data.tag);
                //判断tag在不在既定的范围内
                var tagList = ['御宅','逗趣','绅士','番剧','游戏','音乐','圈子','生活','快看'];
                //if(tagList.indexOf(res.data.data.tag) == -1){
                //    //如果不在，直接显示此时的tag值
                //    //$('#resource_add_type1 option:checked').text(res.data.data.tag);
                //    $('#resource_add_type1 option:checked').text(res.data.data.tag);
                //}else{
                //    $("#resource_add_type1 option[value='" + res.data.data.tag + "']").attr('selected', true);
                //    //$('#resource_add_type1 option:checked').text(res.data.data.tag);
                //}
                $('#resource_add_type1 option:checked').text(res.data.data.tag);
                $('#resource_add_type2 option:checked').text(res.data.data.tagSecond);
                $('#resource_add_type3 option:checked').text(res.data.data.tagThird);
                //另外两个分类的显示
                $("input[name='push_status'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }

        //获取分类选项
        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }


        /**
         * 点击保存的操作
         * @returns {boolean}
         */
        $scope.pushPost = function () {
            $scope.data.pushId = pushId;
            $scope.data.type = $('input:radio[name=type]:checked').val();
            $scope.data.major = $('#push_major option:checked').val();
            $scope.data.start = $('#push_major_time1').val();
            $scope.data.end = $('#push_major_time2').val();
            $scope.data.minor = $('#push_minor option:checked').val();
            $scope.data.first = $('#push_minor_time1').val();
            $scope.data.last = $('#push_minor_time2').val();
            $scope.data.tag = $('#resource_add_type1 option:checked').text();
            $scope.data.tagSecond = $('#resource_add_type2 option:checked').text();
            $scope.data.tagThird = $('#resource_add_type3 option:checked').text();

            $scope.data.status = $('input:radio[name=push_status]:checked').val();
            if (!$scope.data.contentId) {
                layer.msg('带红星字段的不能为空');
                return false;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/push/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    if (pushId == 0) {
                            layer.msg('提交成功');
                            setTimeout(function(){
                                //$location.path('/ad/resource');
                                var url = window.location.origin+window.location.pathname+'#/ad/resource';
                                location.href = url;
                                layer.msg('返回成功');
                            },1500)
                        } else {
                            layer.msg('修改成功');
                            setTimeout(function(){
                                window.close();
                                //$('.left .modal').remove();
                            },1500)
                    }
                }else{
                    layer.msg(response.message);
                }
            }).error(function (response) {
                layer.msg(response.message);
            });

        }

        $scope.cancel = function () {
                window.close();
        }

        $scope.pushCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){

                if(pushId){
                    //alert('关闭窗口');
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/ad/resource';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });

        }
    }])

    //作者管理
    .controller('writerCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/writer/writer.html',
                'login.html');
        })
        $('#showPageName').text('查询作者列表......O(∩_∩)O~~');
        sessionStorage.clear();
        var currentPage = 1,
            changeCount = true,
            token = localStorage['token'],
            searchCondition = {};
        var data = {};
        searchCondition = data;
        getListAll(data);

        //查询所有
        $scope.writerSelectAll = function () {
            var writerId = $('#writer_id').val();
            if (writerId == '') {
                writerId = 0;
            }
            var status = $('#writer_type option:checked').val();
            if (status == '') {
                status = '0';
            }
            var data = {
                authorId: writerId,
                name: $('#writer_name').val(),
                father: $('#writer_type1 option:checked').text(),
                son: $('#writer_type2 option:checked').text(),
                grandson: $('#writer_type3 option:checked').text(),
                status: status
            }

            getListAll(data);
        }

        function getListAll(data) {
            if (compareObj(data, searchCondition)) {
                changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 20;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/author/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {

                if (res.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = Math.ceil(res.data.count/20) || 1;
                    if(changeCount || currentPage == 1){
                        createPage(20,20,res.data.count);
                        layer.msg('查询到'+res.data.count+'条记录');
                    }
                    $scope.listArr = res.data.map;
                    $.each(res.data.map, function (key, val) {
                        if (val.status == 0) {
                            $scope.showorhide = '隐藏';
                        } else {
                            $scope.showorhide = '显示';
                        }
                        if (val.leak == 0) {
                            $scope.leak = '是';
                        } else {
                            $scope.leak = '否';
                        }
                        if (val.type == 0) {
                            $scope.type = '文章';
                        } else {
                            $scope.type = '视频';
                        }
                    })
                } else {
                    layer.msg(res.data.message);
                }
            })
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        $scope.authorStatus = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }
        $scope.authorLeak = function (leak) {
            if (leak == 0) {
                return '是';
            } else {
                return '否';
            }
        }
        $scope.authorType = function (type) {
            if (type == 0) {
                return '文章';
            } else {
                return '视频';
            }
        }
        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getListAll(searchCondition);
                }
            });
        }

        //显示隐藏操作
        $scope.authorChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });

        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/author/insertOrUpdate',
                data: {status: status, authorId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                   // $scope.listArr.splice($scope.$index, 1);
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功!');
                } else {
                    //jumpLogin(data.data.code);
                    layer.msg(data.data.message);
                }
            })
        }


        //修改按钮
        $scope.writeUpdate = function (authorId) {
            //$location.path('/writer/writerAdd')
            sessionStorage.setItem('type', 1);
            sessionStorage.setItem('authorId', authorId);
            //var url = '';
            var url = window.location.origin+window.location.pathname+'#/writer/writerAdd';
            window.open(url);
        }


        //新增按钮
        $scope.writerAdd = function () {
            $location.path('/writer/writerAdd')
            sessionStorage.setItem('type', 0)
        }


        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }
    }])

    //作者管理新增和修改
    .controller('writerAddCtrl', ['$scope', '$location', '$http', 'postData', '$timeout',function ($scope, $location, $http, postData,$timeout) {
        $scope.data = {};
        var type = sessionStorage.getItem('type'),
            token = localStorage['token'],
            authorId = '';


        if (type=='1') {
            $scope.msg = '修改';
            $scope.showBack = true;
            $('#showPageName').text('修改作者信息......O(∩_∩)O~~');
            authorId = sessionStorage.getItem('authorId');
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增作者......O(∩_∩)O~~');
            authorId = 0;
        }

        if (!authorId) {
            $scope.data = {
                icon:'',
                name: '',
                summary: '',
                weight: ''
            };
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/author/selectOne',
                params: {authorId: authorId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                $scope.data = {
                    name: res.data.data.name,
                    summary: res.data.data.summary,
                    icon:res.data.data.icon,
                    weight: res.data.data.weight
                }

                $('#writer_type1 option:checked').text(res.data.data.father);
                $('#writer_type2 option:checked').text(res.data.data.son);
                $('#writer_type3 option:checked').text(res.data.data.grandson);

                $("input[name='author_type'][value='" + res.data.data.type + "']").attr('checked', true);
                $("#author_tag option[value='" + res.data.data.leak + "']").attr('selected', 'selected');
                $("input[name='author_status'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }




        //表单数据提交
        $scope.authorPost = function () {
            $scope.data.authorId = authorId || 0;
            $scope.data.father = $('#writer_type1 option:checked').text();
            $scope.data.son = $('#writer_type2 option:checked').text();
            $scope.data.grandson = $('#writer_type3 option:checked').text();
            $scope.data.type = $('input:radio[name=author_type]:checked').val();
            $scope.data.leak = $('#author_tag option:checked').val();
            $scope.data.status = $('input:radio[name=author_status]:checked').val();
            if (!$scope.data.name) {
                layer.msg('带红星的字段不能为空');
                return false;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/author/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result && response.result == true) {
                    $('.preserve_btn').attr('disabled', true);
                    if (!authorId) {
                            layer.msg('提交成功!');
                            setTimeout(function(){
                                var url = window.location.origin + window.location.pathname +'#/writer';
                                   window.location.href = url;
                            },1500)
                        } else {
                            layer.msg('修改成功!')
                            setTimeout(function(){
                                window.close();
                            },1500)
                        }
                }
                else {
                    layer.msg(response.data.message);
                }
            }).error(function (response) {
                {
                    layer.msg(response.data.message);
                }
            });
        }


        //上传头像图片
        $('#upload_author_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0);

            }).catch(function (err) {
                console.log(err);
            });

            $(this).val('');
        });

        $scope.videoCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                if(authorId){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/writer';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });
        }

        getList($scope);
        function getList($scope) {
            $http.get('code/server/common/list.json')
                .then(function success(data) {
                    $scope.list = data.data;
                })
        }

        $scope.cancel = function () {
            //$location.path('/writer');
            //$('.left .modal').remove();
            window.close();

        }


        $scope.showPhotos  = function(link){
            if(link){
                //第一张图片的删除
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.icon = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }

    }])


    //签到管理
    .controller('signCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/sign/sign.html',
                'login.html');
        })
        $('#showPageName').text('查询签到......O(∩_∩)O~~');
        sessionStorage.clear();
        var currentPage = 1,
            changeCount = true,
            token = localStorage['token'],
            searchCondition = {}; //查询条件。判断查询条件有没有更改，从而判断需不需要当前页数重新变成1；
        //获取一下当前的前一个月
        var lastYear = new Date().getMonth() == 0 ? new Date().getFullYear() - 1 : new Date().getFullYear(),
            lastDay = new Date().getDate() > 10 ? new Date().getDate() : ('0' + new Date().getDate()),
            lastMonth = new Date().getMonth() == 0 ? 12 : (new Date().getMonth() > 10 ? new Date().getMonth() : ('0' + new Date().getMonth())),
            lastSearchDate = lastYear + '-' + lastMonth + '-' + lastDay;

        var data = {
            start: lastSearchDate || getNowDate(),
            end: '2100-01-01',
            status: $('#sign_type option:checked').val(),
            size: 1000,
            num: currentPage
        };
        searchCondition = data;
        getAllList(data);

        //查询所有
        $scope.signSelectAll = function () {
            var startDate = $('#sign_date1').val();
            var endDate = $('#sign_date2').val();
            if (startDate == '') {
                startDate = lastSearchDate || getNowDate();
            }
            if (endDate == '') {
                endDate = '2100-01-01';
            }

            data = {
                start: startDate,
                end: endDate,
                status: $('#sign_type option:checked').val(),
                size: 1000,
                num: currentPage
            };

            getAllList(data);
        }
        function getAllList(data) {
            //判断此时的data和之前的查询条件是否一致
            if (compareObj(data, searchCondition)) {
                changeCount = false;
            } else {
                changeCount = true;
                searchCondition = data;
                currentPage = 1;
            }
            data.num = currentPage;
            data.size = 1000;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/mind/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if (res.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = Math.ceil(res.data.count / 1000 || 1);
                    if(changeCount || currentPage == 1){
                        createPage(1000,20,res.data.map.length);
                        layer.msg('查询到'+res.data.map.length+'条记录');
                    }
                    $scope.listArr = res.data.map;
                } else {
                    layer.msg(res.data.message);
                }
            })
        }
        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }


        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }

        //显示隐藏操作
        $scope.signChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });

        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/mind/insertOrUpdate',
                data: {status: status, picId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    //$scope.listArr.splice($scope.$index, 1);
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功!');
                } else {
                    //jumpLogin(data.data.code);
                }
            })
        }

        //新增按钮
        $scope.signAdd = function () {
            $location.path('/sign/signAdd');
            sessionStorage.setItem('type', 0)
        }
        //跳转到修改界面
        $scope.signUpdate = function (picId) {
            //$location.path('/sign/signAdd');
            sessionStorage.setItem('type', 1);
            sessionStorage.setItem('picId', picId);
            var url = window.location.origin+window.location.pathname+'#/sign/signAdd';
            window.open(url);
        }
    }])

    //签到新增
    .controller('signAddCtrl', ['$scope', '$location', '$http', 'postData', '$timeout',function ($scope, $location, $http, postData,$timeout) {
        $scope.data = {};
        var type = sessionStorage.getItem('type'),
            token = localStorage['token'],
            picId = '';
        if (type=='1') {
            $scope.msg = '修改';
            $scope.showBack = true;
            $('#showPageName').text('修改签到......O(∩_∩)O~~');
            picId = sessionStorage.getItem('picId') || 0;
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增签到......O(∩_∩)O~~');
            picId = 0;
        }

        if (picId == 0) {
            $scope.data = {
                rhesis: '',
                date:getNowDate().replace('T',' '),
                link:'',
                registration: ''
            }
            $('#sign_releaseTime').val($scope.data.date);
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/mind/selectOne',
                params: {picId: picId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                $scope.data = {
                    rhesis: res.data.data.rhesis,
                    date:res.data.data.date,
                    link:res.data.data.link,
                    registration: res.data.data.registration
                }
                //if($scope.data.date && $scope.data.date.length <= 10 ){
                //    $scope.data.date = $scope.data.date +' 00:00:00';
                //}
                $('#sign_releaseTime').val($scope.data.date);
                $("input[name='sign_add_type'][value='" + res.data.data.status + "']").attr('checked', true);
            })
        }

        //表单提交
        $scope.signPost = function () {
            $scope.data.picId = picId;
            $scope.data.date = $('#sign_releaseTime').val();
            $scope.data.status = $('input:radio[name=sign_add_type]:checked').val();
            if (!$scope.data.rhesis  || !$scope.data.registration || !$scope.data.date) {
                layer.msg('带红星字段不能为空!');
                return false;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/mind/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    if (picId == 0) {
                        layer.msg('提交成功');
                        setTimeout(function(){
                            var url = window.location.origin + window.location.pathname +'#/sign';
                            window.location.href = url;
                        },1500)
                    } else {
                        layer.msg('修改成功');
                        setTimeout(function(){
                            window.close();
                        },1500)
                    }
                }else{
                    layer.msg(response.message);
                }
            }).error(function (response) {
                layer.msg(response.message);
            });
        }

        //上传头像图片
        $('#upload_sign_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.link = iconUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                layer.msg(err);
            });
            $(this).val('');
        });

        $scope.signCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){

                if(picId){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/sign';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });
        }

        $scope.cancel = function () {
            window.close();
        }

        $scope.showPhotos = function(link){
            if(link){
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.link = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }


    }])


    //活动管理
    .controller('activityCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/activity/activity.html',
                'login.html');
        })

        $('#showPageName').text('查询活动列表......O(∩_∩)O~~');
        sessionStorage.clear();
        var currentPage = 1,
            data = {size: 1000, num: currentPage},
            token = localStorage['token'],
            changeCount = true,
            searchCondition = data;
           getAllList(data);
        //查询
        $scope.activitySelectAll = function () {
            var type = $('#activity_type option:selected').val();
            var activityId = $('#activityId').val();
            if (activityId == '') {
                activityId = 0;
            }
            var data = {
                activityId: activityId,
                title: $('#activityTitle').val(),
                start: $('#activityStart').val(),
                end: $('#activityEnd').val(),
                type: type,
                status: $('#activity_status option:checked').val()
            }
            getAllList(data);
        }

        function getAllList(data) {
            if(compareObj(data,searchCondition)){
                changeCount = false;
            }else{
                searchCondition = data;
                changeCount = true;
                currentPage = 1;
            }
            data.num = currentPage;
            data.size = 1000;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/activity/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if (res.data.result == true) {
                    $scope.listArr = res.data.map;
                    $scope.currentPage = currentPage;
                    $scope.allPage = 1;
                    if(changeCount || currentPage == 1){
                        createPage(1000,20,res.data.map.length);
                        layer.msg('共找到'+res.data.map.length+'条记录!');
                    }

                    $.each(res.data.map, function (key, val) {
                        if (val.status == 0) {
                            $scope.type = '隐藏';
                        } else {
                            $scope.type = '显示';
                        }
                    })
                } else {
                    layer.msg(res.data.message);
                }
            })
        }


        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }
        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }

        //显示隐藏操作
        $scope.activityChange = function (status, id, $scope) {
            //if (status == 1) {
            //    if (confirm('确定显示吗？')) {
            //        status = 0;
            //        showOrHide(status, id, $scope);
            //    }
            //} else {
            //    if (confirm('确定隐藏吗?')) {
            //        status = 1;
            //        showOrHide(status, id, $scope);
            //    }
            //}
            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });
        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/activity/insertOrUpdate',
                data: {status: status, activityId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    //$scope.listArr.splice($scope.$index, 1);
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功!');
                } else {
                    jumpLogin(data.data.code);
                }
            })
        }


        $scope.activityAdd = function () {
            $location.path('/activity/activityAdd');
            sessionStorage.setItem('type', 0);
        }

        $scope.activityUpdate = function (activityId) {
            //$location.path('/activity/activityAdd');
            sessionStorage.setItem('type', 1);
            sessionStorage.setItem('activityId', activityId);
            var url = window.location.origin+window.location.pathname+'#/activity/activityAdd';
            window.open(url);
        }

    }])

    //活动新增
    .controller('activityAddCtrl', ['$scope', '$location', '$http', 'postData', '$timeout',function ($scope, $location, $http, postData,$timeout) {

        $scope.data = {};
        var type = sessionStorage.getItem('type'),
            activityId = '',
            token = localStorage['token'];
        if (type == '1') {
            $scope.msg = '修改';
            activityId = sessionStorage.getItem('activityId');
            $scope.showBack = true;
            $('#showPageName').text('修改活动......O(∩_∩)O~~');
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增活动......O(∩_∩)O~~');
        }
        if (!activityId) {
            activityId = 0;
            $scope.data = {
                title: '',
                link: '',
                icon:'',
                audioTitle: '',
                audioAuthor: '',
                audioIcon:'',
                audioLink:'',
                weight: ''
            }
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/activity/selectOne',
                params: {activityId: activityId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if(res.data.result && res.data.result == true){

                    $scope.data = res.data.data;
                    $('#editor-trigger').append($(res.data.data.summary));
                    //$('input:radio[name=activity_add_type]:checked').val(res.data.data.type);
                    $("input[name='activity_add_type'][value='" + res.data.data.type + "']").attr('checked', true);
                    $('#activity_releaseTime').val(res.data.data.releaseTime);
                    $('#activity_endTime').val(res.data.data.end);
                    $('#activity_send option:checked').val(res.data.data.send);
                    $("input[name='activity_add_status'][value='" + res.data.data.status + "']").attr('checked', true);
                }else{
                    layer.msg(res.data.message);
                }
            })
        }

        //表单提交
        $scope.activityPost = function () {
            $scope.data.activityId = activityId;
            $scope.data.summary = $('#editor-trigger').html();
            $scope.data.type = $('input:radio[name=activity_add_type]:checked').val();
            $scope.data.releaseTime = $('#activity_releaseTime').val() || '';
            $scope.data.end = $('#activity_endTime').val()|| '';
            $scope.data.send = $('#activity_send option:checked').val();
            $scope.data.status = $('input:radio[name=activity_add_status]:checked').val();
            if (!$scope.data.title) {
                layer.msg('带红星字段不能为空!');
                $('.layui-layer-content').css({
                    'background-color':'#393D49',
                    color:'#fff'
                });
                return false;
            }
            //处理内容中的图片
            //var flag = true;
            //$.each( $('#editor-trigger img'), function (key, val) {
            //    //获取路径
            //    var src= val.src;
            //    if(src){
            //        //判断图片是否存到自己的服务器
            //        if(src.indexOf('https://ddup-img1.oss-cn-hangzhou.aliyuncs.com') > -1){
            //        }else{
            //            flag = false;
            //            layer.alert('请检查第'+(key+1)+'张图片的路径，保证图片为本地上传！');
            //        }
            //    }
            //})
            //if(!flag){
            //    return;
            //}
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/activity/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    if (activityId == 0) {
                        layer.msg('提交成功!');
                        setTimeout(function(){
                            var url = window.location.origin + window.location.pathname +'#/activity';
                            window.location.href = url;
                        },1500)
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    } else {
                        layer.msg('修改成功!')
                        setTimeout(function(){
                            window.close();
                        },1500)
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    }
                }else{
                    layer.msg(response.data.message);
                }
            }).error(function (response) {
                layer.msg(response.data.message);
            });
        }


        //上传音频图片和头像
        $('#upload_activity_Icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0);

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#upload_activity_audioIcon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.audioIcon = iconUrl[0].replace('http', 'https');
                },0);

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#activity_add_audio').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            $('#activity_col_file span').text('正在上传...');
            client.multipartUpload(storeAs, file).then(function (result) {
                var audioUrl = result.res.requestUrls[0].split('?');
                if (audioUrl.length > 0) {
                    $('#activity_col_file span').text('上传成功!');
                }
                $timeout(function(){
                    $scope.data.audioLink = audioUrl[0].replace('http', 'https');
                },0)

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $('#activity_releaseTime').val(getNowFormatDate().replace('T',' '));

        $scope.activityCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                if(activityId != 0){
                    //alert('关闭窗口');
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/activity';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });
            $('.layui-layer-content').css({
                'background-color':'#393D49',
                color:'#fff'
            });
        }

        $scope.cancel = function () {
            window.close();
        }

        $scope.showPhotos = function(link,type){
            switch (type){
                case 'pic':
                    layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        $timeout(function(){
                            $scope.data.icon = '';
                        },0);
                        layer.msg('删除成功', {icon: 1});
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    }, function(){

                    });
                    break;
                case 'audioPic':
                    layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        $timeout(function(){
                            $scope.data.audioIcon = '';
                        },0);
                        layer.msg('删除成功', {icon: 1});
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    }, function(){

                    });
                    break;
                case 'audioLink':
                    layer.confirm('确定删除音频吗?', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        //判断是删的哪张
                        $timeout(function(){
                            $scope.data.audioLink = '';
                        },0);
                        layer.msg('删除成功', {icon: 1});
                        $('.layui-layer-content').css({
                            'background-color':'#393D49',
                            color:'#fff'
                        });
                    }, function(){

                    });
                    break;
            }
        }
    }])


    //商城管理
    .controller('mallCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/mall/mall.html',
                'login.html');
        })

        $('#showPageName').text('查询商品列表......O(∩_∩)O~~');
        sessionStorage.clear();
        //获取一下当前的前一个月
        var lastYear = new Date().getMonth() == 0 ? new Date().getFullYear() - 1 : new Date().getFullYear(),
            lastDay = new Date().getDate() > 10 ? new Date().getDate() : ('0' + new Date().getDate()),
            lastMonth = new Date().getMonth() == 0 ? 12 : (new Date().getMonth() > 10 ? new Date().getMonth() : ('0' + new Date().getMonth())),
            lastSearchDate = lastYear + '-' + lastMonth + '-' + lastDay;
        var currentPage = 1,
            changeCount = true,
            token = localStorage['token'],
            searchCondition = {};
        var data = {
            name: $('#mallName').val(),
            type: $('#mall_type option:checked').val(),
            status: $('#mall_status option:checked').val(),
            start: lastSearchDate,
            end: $('#mall_date_end').val()
        }
        searchCondition = data;
        getAllList(data);
        //查询
        $scope.mallSelectAll = function () {
            var data = {
                name: $('#mallName').val(),
                type: $('#mall_type option:checked').val(),
                status: $('#mall_status option:checked').val(),
                start: $('#mall_date_start').val(),
                end: $('#mall_date_end').val()
            };
            getAllList(data);
        }
        function getAllList(data) {
            if (compareObj(searchCondition, data)) {
                changeCount = false;
            } else {
                searchCondition = data;
                currentPage = 1;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 20;
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/prizes/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if (res.data.result == true) {
                    $scope.currentPage = currentPage;
                    $scope.allPage = Math.ceil(res.data.count / 20 || 1);
                    if(changeCount || currentPage == 1){
                        createPage(20,20,res.data.map.length);
                        layer.msg('共找到'+res.data.map.length+'条记录!');
                    }
                    $scope.listArr = res.data.map;
                    $.each(res.data.map, function (key, val) {
                        if (val.status == 0) {
                            $scope.type = '隐藏';
                        } else {
                            $scope.type = '显示';
                        }
                    })
                } else {
                    layer.msg(res.data.message);
                }
            })
        }
        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            //if (obj1.length == obj2.length) {
            //    for (var i in obj1) {
            //        if (obj2[i] && obj1[i] == obj2[i]) {
            //
            //        } else {
            //            flag = false;
            //        }
            //    }
            //} else {
            //    flag = false;
            //}
            if(obj1.name != obj2.name || obj1.type != obj2.type || obj1.status != obj2.status || obj1.start != obj2.start || obj1.end != obj2.end){
                flag = false;
            }
            return flag;
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }

        //显示隐藏操作
        $scope.mallChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定显示吗？':'确定隐藏吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });
        }
        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/prizes/insertOrUpdate',
                data: {status: status, prizesId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功!');
                } else {
                    layer.msg(data.data.message);
                }
            })
        }

        $scope.mallAdd = function () {
            $location.path('/mall/mallAdd');
            sessionStorage.setItem('type', 0)
        }

        $scope.mallUpdate = function (prizesId) {
            sessionStorage.setItem('type', 1);
            sessionStorage.setItem('prizesId', prizesId);
            var url = window.location.origin+window.location.pathname+'#/mall/mallAdd';
            window.open(url);
        }

    }])

    //商城管理增加
    .controller('mallAddCtrl', ['$scope', '$location', '$http', 'postData','$timeout', function ($scope, $location, $http, postData,$timeout) {
        $scope.data = {};
        var type = sessionStorage.getItem('type'),
            token = localStorage['token'],
            prizesId = '';
        if (type == '1') {
            $scope.msg = '修改';
            $scope.showBack = true;
            $('#showPageName').text('修改商品......O(∩_∩)O~~');
            prizesId = sessionStorage.getItem('prizesId');
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增商品......O(∩_∩)O~~');
        }


        if (!prizesId) {
            prizesId = 0;
            $scope.data = {
                name: '',
                coin: '',
                count: '',
                attend: '0',
                attendCount: '0',
                times: '1',
                weight: ''
            }
            $('#mall_start').val(getNowFormatDate().replace('T',' '));
            $('#mall_end').val(getNowFormatDate().replace('T',' '));
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/prizes/selectOne',
                params: {prizesId: prizesId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if(res.data.result && res.data.result == true){
                    $scope.data = {
                        name: res.data.data.name,
                        coin: res.data.data.coin,
                        icon:res.data.data.icon,
                        summaryIcon:res.data.data.summaryIcon,
                        count: res.data.data.count,
                        attend: res.data.data.attend,
                        attendCount: res.data.data.attendCount,
                        times: res.data.data.times,
                        weight: res.data.data.weight,
                        gainCoin: res.data.data.gainCoin
                    }
                    $('#mall_summary').val(res.data.data.summary);
                    $('#mall_start').val(res.data.data.start);
                    $('#mall_end').val(res.data.data.end);
                    $('input[name="mall_type"][value="' + res.data.data.type + '"]').attr('checked', true)
                    $("input[name='mall_add_status'][value='" + res.data.data.status + "']").attr('checked', true);
                }else{
                    layer.msg(res.data.message);
                }

            })
        }

        //提交数据
        $scope.mallPost = function () {
            $scope.data.prizesId = prizesId;
            $scope.data.summary = $('#mall_summary').val();
            $scope.data.start = $('#mall_start').val() || '';
            $scope.data.end = $('#mall_end').val() || '';
            $scope.data.type = $('input:radio[name=mall_type]:checked').val();
            $scope.data.status = $('input:radio[name=mall_add_status]:checked').val();
            if (!$scope.data.name || $scope.data.start == '' ||
                $scope.data.end == '' || ($scope.data.coin && $scope.data.coin<0) || ($scope.data.gainCoin && $scope.data.gainCoin<0)
                || ($scope.data && $scope.data.count<0) || $scope.data.coin==undefined || $scope.data.gainCoin==undefined || $scope.data.count == undefined) {
                layer.msg('带红星字段不能为空!');
                return false;
            }
            if(!$scope.data.times){
                $scope.data.times = 1;
            }
            if(!$scope.data.attend){
                $scope.data.attend = 0;
            }
            if(!$scope.data.attendCount){
                $scope.data.attendCount = 0;
            }
            if($scope.data.times == 0){
                layer.msg('兑换次数不能填0');
                return false;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/prizes/insertOrUpdate',
                data: $scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                if (response.result == true) {
                    if (prizesId == 0) {
                        layer.msg('提交成功!');
                        setTimeout(function(){
                            var url = window.location.origin + window.location.pathname +'#/mall';
                            window.location.href = url;
                        },1500)
                    } else {
                        layer.msg('修改成功!')
                        setTimeout(function(){
                            window.close();
                        },1500)
                    }
                }else{
                    layer.msg(response.message);
                }
            }).error(function (response) {
                layer.msg(response.message);
            });
            //判断兑换次数
            //var promise = postData.post('/management/prizes/insertOrUpdate', $scope.data);
            //$('.preserve_btn').attr('disabled', true);
            //promise.then(function (response) {
                //if (response.result == true) {
                //    $('.preserve_btn').attr('disabled', false);
                //    if (prizesId == 0) {
                //        confirm('提交成功!');
                //        $location.path('/mall');
                //        $('.left .modal').remove();
                //    } else {
                //        layer.msg('修改成功!');
                //        setTimeout(function(){
                //            window.close();
                //        },1500)
                //    }
                //} else {
                //    jumpLogin(response.code);
                //}
                //layer.msg(response.message);
            //})
        }


        //上传图片
        $('#upload_mall_Icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0);

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        $('#upload_mall_summaryIcon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;

            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
               $timeout(function(){
                   $scope.data.summaryIcon = iconUrl[0].replace('http', 'https');
               },0)

            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });


        /**
         * 点击小图查看大图显示
         * @param link
         */
        $scope.showPhotos = function(link,type){
            layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                if(type=='icon'){
                    $timeout(function(){
                        $scope.data.icon = '';
                    },0);
                }else{
                    $timeout(function(){
                        $scope.data.summaryIcon = '';
                    },0);
                }
                layer.msg('删除成功', {icon: 1});
            }, function(){

            });
        }

        $scope.mallCancel = function () {
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){

                if(prizesId != 0){
                    //alert('关闭窗口');
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/mall';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });

        }

        $scope.cancel = function () {
            window.close();
        }
    }])


    //兑换管理
    .controller('exchangeCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/exchange/exchange.html',
                'login.html');
        })

        $('#showPageName').text('查询兑换列表......O(∩_∩)O~~');
        sessionStorage.clear();
        var currentPage = 1,
            changeCount = true,
            token = localStorage['token'],
            serachCondition = {};

        //getAllList(data);
        getList();
        //查询
        $scope.exSelectAll = function () {
            var jottaId = $('#ex_id').val();
            if (jottaId == '') {
                jottaId = 0;
            }
            var data = {
                jottaId: jottaId,
                name: $('#ex_product_name').val(),
                type: $('#ex_product_property option:checked').val(),
                status: $('#ex_product_type option:checked').val(),
                start: $('#ex_start').val(),
                end: $('#ex_end').val()
            }

            getList(data);
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }


        function getList(){
            var jottaId = $('#ex_id').val();

            if (jottaId == '') {
                jottaId = 0;
            }
            var data = {
                jottaId: jottaId,
                name: $('#ex_product_name').val(),
                //type: $('#ex_product_property option:checked').val(),
                status: $('#ex_product_type option:checked').val(),
                start: $('#ex_start').val(),
                end: $('#ex_end').val()
            }
            getAllList(data);
        }



        function getAllList(data) {
            if(compareObj(data,serachCondition)){
                changeCount = false;
            }else{
                currentPage = 1;
                serachCondition = data;
                changeCount = true;
            }
            data.num = currentPage;
            data.size = 20;
            $http({
                method: 'GET',
                //url: 'http://101.37.32.213:18080/management/jotta/select',
                url: window.reqUrl+'/management/jotta/select',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if (res.data.result == true) {
                    $scope.selectAll = true;
                    $scope.listArr = res.data.map;
                    $scope.currentPage = currentPage;
                    $scope.allPage = Math.ceil(res.data.count / 20 || 1);
                    if(changeCount || currentPage == 1){
                        createPage(20,20,res.data.count);
                        layer.msg('查询到'+res.data.count+'条记录！');
                    }
                    $.each(res.data.map, function (key, val) {
                        if (val.status == 0) {
                            $scope.type = '隐藏';
                        } else {
                            $scope.type = '显示';
                        }
                    })
                } else {
                    layer.msg(res.data.message)
                }
            })
        }

        $scope.change = function (status) {
            if (status == 0) {
                return '未发货';
            } else {
                return '已发货';
            }
        }

        //显示隐藏操作
        $scope.mallChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成未发货吗？':'确定改成已发货吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    showOrHide(0, id, $scope);
                }else{
                    showOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        function showOrHide(status, id, $scope) {
            $http({
                method: 'POST', //http://localhost:8080/management/jotta/update?jottaId=12&status=0
                url: window.reqUrl+'/management/jotta/update',
                data: {status: status, jottaId: id},
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(data) {
                if (data.data.result == true) {
                    //$scope.listArr.splice($scope.$index, 1);
                    if($scope.listArr[$scope.$index].status == 0){
                        $scope.listArr[$scope.$index].status = 1;
                    }else{
                        $scope.listArr[$scope.$index].status = 0;
                    }
                    layer.msg('操作成功!');
                } else {
                    jumpLogin(data.data.code);
                }
            })
        }


        $scope.exUpdate = function (jottaId) {
            //$location.path('/exchange/exchangeAdd');
            sessionStorage.setItem('jottaId', jottaId);
            var url = window.location.origin+window.location.pathname+'#/exchange/exchangeAdd';
            window.open(url);
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(serachCondition);
                }
            });
        }



        //批量进行选中/取消选中状态
        $scope.selectAll = true;   // true进行全选  false 取消全选
        $scope.resolveSel = function(){
            if($scope.selectAll){
                //进行全部选中操作
                $.each($('input[name="cho"]'),function(i,n){
                    $(n).prop('checked',true);
                })
                $scope.selectAll = false;
            }else{
                //进行全部取消选中操作
                //layer.msg('进行取消操作');
                $.each($('input[name="cho"]'),function(i,n){
                    $(n).prop('checked',false);
                })
                $scope.selectAll = true;
            }
        }
        //逐个进行选项的处理   仅仅批处理未发货到已发货的状态
        $scope.resolveAll = function(){
             //获取真实的待操作的数据
            var count = 0,
                selectCount = 0,
                flag = true,
                arr = [];
            $.each($('input[name="cho"]'),function(i,n){
                if($(n).prop('checked')){
                    selectCount++;
                    //未发货
                    if($scope.listArr[i].status == 0){
                        arr[count] = $scope.listArr[i];
                        arr[count].index = i;
                        count++;
                    }else{
                        console.log($scope.listArr[i].status);
                        layer.msg('包含"已发货"的处理！');
                        flag = false;
                        return;
                    }
                }
            })

            if(selectCount == 0){
                layer.msg('请选择要处理的记录!');
            }else{
                if(flag){
                    resolveChoice(arr);
                }
            }
        }

        //进行最终选项的处理
        function resolveChoice(arr){
            var itemList = {
                id:[],  //记录id
                index:[] //记录对应的索引
            };
            $.each(arr,function(index,item){
                itemList.id.push(item.jottaId);
                itemList.index.push(item.index);
            })
            console.log(itemList);
        }

        /**
         * 处理之后数据的更改，界面样式的更改
         */
        function afterResolve(arr){

        }
    }])

    //兑换管理新增
    .controller('exchangeAddCtrl', ['$scope', '$location', '$http', 'postData', function ($scope, $location, $http, postData) {
        $('#showPageName').text('查询兑换......O(∩_∩)O~~');
        $scope.data = {
            jottaId: '',
            productName: '',
            name: '',
            tel: '',
            qq: '',
            address: ''
        };
        var jottaId = sessionStorage.getItem('jottaId'),
            token = localStorage['token'];

        $http({
            method: 'GET',
            url: window.reqUrl+'/management/jotta/orderDetail/'+jottaId,
            //params: jottaId,
            headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
        }).then(function success(res) {
            if(res.data.result && res.data.result == true){
                $scope.data = res.data.data;
                //处理样式
                $("input[name='addType'][value='" + $scope.data.status + "']").attr('checked', true);
            }
        })

        // 是否发货  status


        //提交数据

        //$scope.exPost = function () {
        //    $scope.data.jottaId = sessionStorage.getItem('jottaId');
        //    var promise = postData.post('management/jotta/orderDetail/', $scope.data);
        //    promise.then(function (response) {
        //        if (response.result == true) {
        //            if (jottaId == 0) {
        //                if (confirm('提交成功!')) {
        //                    $location.path('/exchange');
        //                    $('.left .modal').remove();
        //                }
        //            }
        //        } else {
        //            jumpLogin(response.code);
        //        }
        //    })
        //}

        //$scope.exCancel = function () {
        //    if (confirm('请确保提交数据，返回之后数据会清空，确定取消吗？')) {
        //        $location.path('/exchange');
        //        $('.left .modal').remove();
        //    }
        //}

        $scope.cancel = function () {
            window.close();
        }

    }])

    //专题管理
    .controller('subjectCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {

    }])
    .controller('subjectAddCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {

    }])

    //推送管理
    .controller('pushCtrl',['$scope', '$location', '$http', function ($scope, $location, $http) {
        //检查登录状态
        $scope.$on('$routeChangeStart', function () {
            loginCheck('code/view/push/push.html',
                'login.html');
        })
        $('#showPageName').text('查询推送列表......O(∩_∩)O~~');
        var data ={

        },
            changeCount = true,
            currentPage = 1,
            token = localStorage['token'],
            searchCondition = data;

   getAllList(data);
        function getAllList(data){
            if(compareObj(data,searchCondition)){
                changeCount = false;
            }else{
                changeCount = true;
                searchCondition = data;
                currentPage = 1;
            }
            data.pageNo = currentPage;
            data.pageSize = 1000;
            //获取列表数据
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/contentPush/getContentPushList',
                params: data,
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                if (res.data.code == '0') {
                    $scope.listArr = res.data.result;
                    $scope.currentPage = 1;
                    $scope.allPage = 1;
                    if(changeCount || currentPage==1){
                        createPage(1000,20,res.data.result.length);
                        layer.msg('查询到'+res.data.result.length+'条记录！');
                    }
                    $.each(res.data.result, function (key, val) {
                        if (val.status == 0) {
                            $scope.type = '隐藏';
                        } else {
                            $scope.type = '显示';
                        }
                    })
                } else {
                    //alert(res.message);
                    layer.msg(res.data.message);
                }
            })
        }



        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if (obj1.length == obj2.length) {
                for (var i in obj1) {
                    if (obj1[i] == obj2[i]) {

                    } else {
                        flag = false;
                    }
                }
            } else {
                flag = false;
            }
            return flag;
        }
        $scope.change = function (status) {
            if (status == 0) {
                return '隐藏';
            } else {
                return '显示';
            }
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);
                    getAllList(searchCondition);
                }
            });
        }
        //进行查询
        //进行翻页
        //点击新增
        $scope.pushAdd = function(){
            $location.path('/push/pushAdd');
        }
        //修改
        $scope.pushUpdate = function(id){
            sessionStorage.setItem('pushId', id);
            $location.path('/push/pushAdd');
        }
    }])

    //推送新增
    .controller('pushAddCtrl',['$scope','$location','$http','postData','$timeout',function($scope,$location,$http,postData,$timeout){

        $scope.data = {};
        var type = sessionStorage['type'],
            pushId= '',
            token = localStorage['token'];
        if (type == '1') {
            $scope.msg = '修改';
            $scope.showBack = false;
            $('#showPageName').text('修改推送......O(∩_∩)O~~');
            pushId = sessionStorage['pushId'];
        } else {
            $scope.msg = '新增';
            $scope.showBack = false;
            $('#showPageName').text('新增推送......O(∩_∩)O~~');
        }


        if (!pushId) {
            pushId = 0;
            $scope.data = {
                "contentId":'',
                "contentType":'', //contentType 是 文章 视频 活动的分类 0 1 2
                "icon":"",
                "pushTime":"", //2017-04-16 09:06:39
                "status":1,
                "subTitle":"",
                "title":""
            };
        } else {
            $http({
                method: 'GET',
                url: window.reqUrl+'/management/contentPush/getPushInfo',
                params: {pushId: pushId},
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token}
            }).then(function success(res) {
                var datas = res.data;
                if(datas.code == '0'){
                    if(datas.result){
                      $scope.data = datas.result;
                      $scope.data.contentType = 1;
                      //{
                      //    "contentId":123,
                      //    "contentType":'1', //contentType 是 文章 视频 活动的分类 0 1 2
                      //    "icon":"http://ddup-img2.oss-cn-shanghai.aliyuncs.com/temp/297C6CC0-2BBA-48FB-9D1B-5785529870E7.jpg",
                      //    "pushTime":"2015-05-22 11:12:55", //2017-04-16 09:06:39
                      //    "status":1,
                      //    "subTitle":"副标题",
                      //    "title":"的城市德尔的啦啦"
                      //}
                      $('#adImg_releaseTime').val($scope.data.pushTime);
                      $("select[name='push_tt'][value='" +$scope.data.contentType + "']").attr('checked', true);
                        if($scope.data.icon){
                            $('#adImg_col_icon').append('<img src="' + $scope.data.icon + '" class="push_small_img">');
                        }
                      $("input:radio[name='addType'][value='" +$scope.data.status + "']").attr('checked', true);
                  }
                }
            })
        }

        //图片上传
        $('#upload_push_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.icon = iconUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        //表单提交
        $scope.pushPost = function () {
            //获取提交的数据
            var submitData = {
                "contentId":$scope.data.contentId,
                "contentType":$('#push_type option:checked').val(), //contentType 是 0文章 1视频 2活动的分类
                "icon":$scope.data.icon,
                "pushTime":$('#adImg_releaseTime').val() || '', //2017-04-16 09:06:39
                "status":$('input:radio[name=addType]:checked').val(),
                "subTitle":$scope.data.subTitle,
                "title":$scope.data.title
            }

            if (!submitData.title) {
                layer.msg('带红星字段不能为空!');
                return false;
            }
            if(!submitData.pushTime){
                layer.msg('请输入推送时间');
                return false;
            }
            if(pushId){
                submitData.id = pushId;
            }
            layer.msg('正在提交......');
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/contentPush/add',
                data:submitData,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    if (pushId == 0) {
                        layer.msg('提交成功!');
                        setTimeout(function(){
                            var url = window.location.origin + window.location.pathname +'#/push';
                            window.location.href = url;
                        },1500)
                    } else {
                        layer.msg('修改成功!')
                        setTimeout(function(){
                            window.close();
                        },1500)
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }


        $scope.cancel = function () {
          window.close();
        }

        $scope.pushCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                if(pushId == 0){
                    var url = window.location.origin+window.location.pathname+'#/push';
                    location.href = url;
                    layer.msg('返回成功');
                }else{
                    window.close();
                }
            }, function(){

            });
        }

        $scope.showPhoto = function(link){
            if(link){
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.icon = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }
    }])
    .controller('manageController', ['$scope', function ($scope) {
        $scope.msg = '高级管理';
    }])


     //新增问题界面
    .controller('quesCtrl',['$scope', '$location', '$http',function($scope, $location, $http){
        //┏ (゜ω゜)=☞
        $('#showPageName').text('查询问题列表......┏ (゜ω゜)=☞');

        var changeCount = true,
            token = localStorage['token'],
            currentPage = 1,
            data = {

            },
            searchCodition = data;
        $scope.param ={
            content:'',
            id:'',
        }
        //初始查询
         getList();
        function getList(){
            var data = {
                content:$scope.param.content,
                id:$scope.param.id,
                deleteStatus:$('#ques_status option:selected').val()
            };
            //获取列表内容
            if(compareObj(data,searchCodition)){
                changeCount = false;
            }else{
                changeCount = true;
                currentPage = 1;
                searchCodition = JSON.parse(JSON.stringify(data));
            }
            searchCodition.currentPage = currentPage;
            searchCodition.pageSize = 20;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/randomChat',
                params: searchCodition,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    //
                    if(changeCount){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createPage(20,20,data.result.totalResult);
                    }
                    $scope.list = data.result.entity;
                }
            })
        }

        //查询
        $scope.quesSelectAll = function(){
            getList();
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createPage(pageSize, buttons, total) {
            $(".pagination").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentPage = (pageIndex+1);  //记录此时的页数
                    getList(searchCodition);
                }
            });
        }

        /**
         * 判断两个对象是否一致[单属性]
         * @param obj1
         * @param obj2
         * @returns {boolean}
         */
        function compareObj(obj1, obj2) {
            var flag = true;
            if(obj1.content != obj2.content || obj1.deleteStatus != obj2.deleteStatus || obj1.id != obj2.id){
                flag = false;
            }
            return flag;
        }
        //更改状态
        $scope.articleChange = function (status, id, $scope) {
            if (status == 1) {
                layer.confirm('确定显示吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 0;
                    showOrHide(status, id, $scope);

                }, function(){

                });
            } else {
                layer.confirm('确定隐藏吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    status = 1;
                    showOrHide(status, id, $scope);
                }, function(){

                });
            }
        }
        $scope.change = function(status,id,$scope){
            layer.confirm(status==0?'确定无效化吗':'确定有效话吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 0){
                    showOrHide(1, id, $scope);
                }else{
                    showOrHide(0, id, $scope);
                }

            }, function(){

            });
        }

            function showOrHide(status, id, $scope) {
                $http({
                    method: 'POST',
                    url: window.reqUrl+'/management/randomChatUpdate',
                    params: {deleteStatus: status, id: id,content:$scope.list[$scope.$index].content},
                    transformRequest: function (obj) {
                        var str = [];
                        for (var p in obj) {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization': token},
                }).then(function success(data) {
                    if (data.data.code == '0') {
                        if($scope.list[$scope.$index].deleteStatus == 0){
                            $scope.list[$scope.$index].deleteStatus = 1;
                        }else{
                            $scope.list[$scope.$index].deleteStatus = 0;
                        }
                        layer.msg('操作成功');
                    } else {
                        //jumpLogin(data.data.code);
                        layer.msg(data.data.result);
                    }
                })
            }

        //修改问题
        $scope.quesUpdate = function($scope){
            var obj = $scope.list[$scope.$index];
            sessionStorage.setItem('ques',JSON.stringify(obj));
            sessionStorage.setItem('type',1);
            var url = window.location.origin+window.location.pathname+'#/questions/questionsAdd';
            window.open(url);
        }



    }])
    .controller('quesAddCtrl',['$scope', '$location', '$http',function($scope, $location, $http){
      //┏ (゜ω゜)=☞
        var type = sessionStorage['type'],
            token = localStorage['token'],
            obj = {}, //缓存的内容
            quesId = '';
        if(type == 0 || !sessionStorage['ques']){
            $('#showPageName').text('增加问题......┏ (゜ω゜)=☞');
            $scope.msg = '新增';
            $scope.showBack = false;
            quesId = 0;
            $scope.data = {
                content:''
            };
        }else{
            $('#showPageName').text('修改问题......┏ (゜ω゜)=☞');
            $scope.msg = '修改';
            $scope.showBack = true;
            $scope.data = JSON.parse(sessionStorage['ques']);
            quesId = $scope.data.id;
            $("input[name='ques_add_status'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
        }

        //进行内容的保存/更新
        $scope.quesPost = function(){
            if(!$scope.data.content){
                layer.msg('请输入问题内容！');
                return false;
            }
            layer.msg('提交中......');
            if(quesId == 0){
                //进行新增的接口
                $http({
                    method: 'POST',
                    url: window.reqUrl+'/management/randomChat',
                    data:{content:$scope.data.content},
                    transformRequest: function (obj) {
                        var str = [];
                        for (var p in obj) {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
                }).success(function (response) {
                    //成功提交
                    if (response.code == 0) {
                            layer.msg('提交成功!');
                            setTimeout(function(){
                                var url = window.location.origin + window.location.pathname +'#/questions';
                                window.location.href = url;
                            },1500)
                    }else{
                        layer.msg(response.result);
                    }
                }).error(function (response) {
                    layer.msg(response.result);
                });

            }else{
                //进行修改的接口
                $scope.data.deleteStatus = $("input:radio[name='ques_add_status']:checked").val();
                $http({
                    method: 'POST',
                    url: window.reqUrl+'/management/randomChatUpdate',
                    data:$scope.data,
                    transformRequest: function (obj) {
                        var str = [];
                        for (var p in obj) {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
                }).success(function (response) {
                    //成功提交
                    if (response.code == 0) {
                        layer.msg('修改成功!')
                        setTimeout(function(){
                            window.close();
                        },1500)
                    }else{
                        layer.msg(response.result);
                    }
                }).error(function (response) {
                    layer.msg(response.result);
                });
            }
        }

        //取消操作
        $scope.quesCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){

                if(quesId!=0){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/questions';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });

        }


        $scope.cancel = function(){
            window.close();
        }




    }])




    //机器人查看界面集成
    .controller('robotCtrl',['$scope', '$location', '$http',function($scope, $location, $http){
        //┏ (゜ω゜)=☞
        $('#showPageName').text('机器人查询列表......┏ (゜ω゜)=☞');
        var token = localStorage['token'];
        //顶部tab数据
         $scope.tabs = [
            {
                index:0,
                selected:false,
                firstView:true,
                text:'美图'
            },
            {
                index:1,
                selected:false,
                firstView:true,
                text:'表情包'
            },
            {
                index:2,
                selected:false,
                firstView:true,
                text:'唱歌'
            },
            {
                index:3,
                selected:false,
                firstView:true,
                text:'讲故事'
            },
            {
                index:4,
                selected:false,
                firstView:true,
                text:'玩游戏'
            },
            {
                index:5,
                selected:false,
                firstView:true,
                text:'段子'
            },
            {
                index:6,
                selected:false,
                firstView:true,
                text:'拼智商'
            }
        ];


/******************************************模块一：美图的相关内容*****************************************************************/


        //获取图片列表
        var currentImgPage = 1,
            imgSearch = {},
            imgChange = true;   //查询条件是否更改
        function getFirstImg(){
            //是否是第一次查看的状态
            $scope.tabs[0].firstView = false;
            getImgType();
            console.log('第一次美图');
        }
        //获取美图的分类
        function getImgType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/prettyPic/category',
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.optionsImg = data.result;
                    getImgList();
                }
            })
        }

        //正式获取列表的数据
        function getImgList(){
            var imgParam = {
                id:$('#img_id').val(),
                category:parseInt($('#img_type1 option:checked').val()) || '',
                endTime:$('#img_date2').val(),
                startTime:$('#img_date1').val(),
                deleteStatus:parseInt($('#img_status option:checked').val()) || ''
            };
            if(compareImg(imgParam,imgSearch)){
                imgChange = false;
            }else{
                //条件改变
                currentImgPage = 1;
                imgSearch = JSON.parse(JSON.stringify(imgParam));
                imgChange = true;
            }
            imgSearch.pageNo = currentImgPage;
            imgSearch.pageSize = 10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/prettyPic/selectPrettyPic',
                params: imgSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(imgChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createImgPage(10,20,data.result.totalResult);
                    }
                    $scope.imgList = data.result.entity;
                }
            })
        }

        //点击查询按钮
        $scope.imgSelectAll = function(){
            getImgList();
        }

        //判断查询条件有没有改变
        function compareImg(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.endTime != obj2.endTime  || obj1.deleteStatus != obj2.deleteStatus|| obj1.category != obj2.category
                || obj1.startTime != obj2.startTime){
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createImgPage(pageSize, buttons, total) {
            $("#imgPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentImgPage = (pageIndex+1);  //记录此时的页数
                    getImgList(imgSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.imgChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    imgShowOrHide(0, id, $scope);
                }else{
                    imgShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        //获取对应的id
        function getImgId(text){
            var id = '';
            $scope.optionsImg.forEach(function(item,index){
                if(item.label == text){
                    id = item.val;
                    return;
                }
            })
            return id;
        }

        function imgShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.imgList[$scope.$index]));
            var para = {
                category:getImgId(param.categoryLabel),
                deleteStatus:status,
                id:param.id,
                picUrl:param.picUrl,
                weight:param.weight
            };
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/prettyPic/update',
                data:para,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                    if($scope.imgList[$scope.$index].deleteStatus == 0){
                        $scope.imgList[$scope.$index].deleteStatus = 1;
                    }else{
                        $scope.imgList[$scope.$index].deleteStatus = 0;
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
        $scope.imgUpdate = function(item){
            getImgById(item);
        }

          //根据id查询
          function getImgById(item){
              $http({
                  method: 'get',
                  url: window.reqUrl+'/management/prettyPic/selectPrettyPicDetail',
                  params:{id:item.id},
                  headers: {'authorization': token},
              }).then(function success(res) {
                  var data = res.data;
                  if(data.code == 0){
                      var url = window.location.origin+window.location.pathname+'#/addImg';
                      sessionStorage['robotImg'] = JSON.stringify(res.data.result);
                      window.open(url);
                  }else{
                      var url = window.location.origin+window.location.pathname+'#/addImg';
                      sessionStorage['robotImg'] = JSON.stringify(item);
                      window.open(url);
                  }
              })
          }




        //新增美图
       $scope.addImg = function(){
           var url = window.location.origin+window.location.pathname+'#/addImg';
           sessionStorage['robotImg'] = 0;
           window.open(url);
        }






/*******************************************模块二：表情包的相关*********************************************************************/
            //获取图片列表
            var currentMotionPage = 1,
            motionSearch = {},
            motionChange = true;   //查询条件是否更改
        function getFirstMotion(){
            //是否是第一次查看的状态
            $scope.tabs[1].firstView = false;
            getMotionType();
            console.log('第一次表情包');
        }
        //getMotionType();
        //获取美图的分类
        function getMotionType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/picPackage/category',
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.optionsMotion = data.result;
                    getMotionList();
                }
            })
        }

        //正式获取列表的数据
        function getMotionList(){
            var motionParam = {
                id:$('#motion_id').val(),
                endTime:$('#motion_date2').val(),
                category:parseInt($('#motion_type1 option:checked').val())|| '',
                startTime:$('#motion_date1').val(),
                deleteStatus:parseInt($('#motion_status option:checked').val()) || ''
            };

            if(compareMotion(motionParam,motionSearch)){
                motionChange = false;
            }else{
                //条件改变
                currentMotionPage = 1;
                motionSearch = JSON.parse(JSON.stringify(motionParam));
                motionChange = true;
            }
            motionSearch.pageNo = currentMotionPage;
            motionSearch.pageSize =10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/picPackage/selectPicPackage',
                params: motionSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(motionChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createMotionPage(10,20,data.result.totalResult);
                    }
                    $scope.motionList = data.result.entity;
                }
            })
        }

        //点击查询按钮
        $scope.motionSelectAll = function(){
            getMotionList();
        }

        //判断查询条件有没有改变
        function compareMotion(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.endTime != obj2.endTime  || obj1.deleteStatus != obj2.deleteStatus|| obj1.category != obj2.category
                || obj1.startTime != obj2.startTime){
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createMotionPage(pageSize, buttons, total) {
            $("#motionPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentMotionPage = (pageIndex+1);  //记录此时的页数
                    getMotionList(motionSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.motionChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    motionShowOrHide(0, id, $scope);
                }else{
                    motionShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        //获取对应的id
        function getMotionId(text){
            var id = '';
            $scope.optionsMotion.forEach(function(item,index){
                if(item.label == text){
                    id = item.val;
                    return;
                }
            })
            return id;
        }

        function motionShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.motionList[$scope.$index]));
            var para = {
                category:getMotionId(param.categoryLabel),
                deleteStatus:status,
                id:param.id,
                picUrl:param.picUrl,
                weight:param.weight
            };
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/picPackage/update',
                data:para,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                    if($scope.motionList[$scope.$index].deleteStatus == 0){
                        $scope.motionList[$scope.$index].deleteStatus = 1;
                    }else{
                        $scope.motionList[$scope.$index].deleteStatus = 0;
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
        $scope.motionUpdate = function(item){
            getMotionById(item);
        }

        //根据id查询
        function getMotionById(item){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/picPackage/selectPicPackageDetail',
                params:{id:item.id},
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    var url = window.location.origin+window.location.pathname+'#/addMotion';
                    sessionStorage['robotMotion'] = JSON.stringify(res.data.result);
                    window.open(url);
                }else{
                    var url = window.location.origin+window.location.pathname+'#/addMotion';
                    sessionStorage['robotMotion'] = JSON.stringify(item);
                    window.open(url);
                }
            })
        }





//新增表情包
$scope.addMotion = function(){
    var url = window.location.origin+window.location.pathname+'#/addMotion';
    sessionStorage['robotMotion'] = 0;
    window.open(url);
  }

/*******************************************模块三：唱歌的相关*********************************************************************/

        var currentAudioPage = 1,
            audioSearch = {},
            audioChange = true;   //查询条件是否更改


        //正式获取列表的数据
        function getAudioList(){
            var audioParam = {
                id:$('#audio_id').val(),
                songName:$('#audio_title').val(),
                endTime:$('#audio_date2').val(),
                startTime:$('#audio_date1').val(),
                deleteStatus: $('#audio_status option:checked').val()
            };
            if(compareAudio(audioParam,audioSearch)){
                audioChange = false;
            }else{
                //条件改变
                currentAudioPage = 1;
                audioSearch = JSON.parse(JSON.stringify(audioParam));
                audioChange = true;
            }

            audioSearch.pageNo = currentAudioPage;
            audioSearch.pageSize = 10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/song/selectSong',
                params: audioSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(audioChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createAudioPage(10,20,data.result.totalResult);
                    }
                    $scope.audioList = data.result.entity;
                }
            })
        }



        //点击查询按钮
        $scope.audioSelectAll = function(){
            getAudioList();
        }

        //判断查询条件有没有改变
        function compareAudio(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.endTime != obj2.endTime  || obj1.deleteStatus != obj2.deleteStatus|| obj1.songName != obj2.songName
                || obj1.startTime != obj2.startTime){
                flag = false;
            }
            return flag;
        }

        function getFirstAudio(){
            //是否是第一次查看的状态
            $scope.tabs[2].firstView = false;
            getAudioList();
            console.log('第一次唱歌');
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createAudioPage(pageSize, buttons, total) {
            $("#audioPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentAudioPage = (pageIndex+1);  //记录此时的页数
                    getAudioList(audioSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.audioChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    audioShowOrHide(0, id, $scope);
                }else{
                    audioShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        function audioShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.audioList[$scope.$index]));
            if(param.createTime){
                delete  param.createTime;
            }
            if(param.updateTime){
                delete param.updateTime;
            }
            param.deleteStatus = status;
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/song/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                    if($scope.audioList[$scope.$index].deleteStatus == 0){
                        $scope.audioList[$scope.$index].deleteStatus = 1;
                    }else{
                        $scope.audioList[$scope.$index].deleteStatus = 0;
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
        $scope.audioUpdate = function(item){
            getAudioById(item);
        }

        //根据id查询
        function getAudioById(item){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/song/selectSongDetail',
                params:{id:item.id},
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    var url = window.location.origin+window.location.pathname+'#/addAudio';
                    sessionStorage['robotAudio'] = JSON.stringify(res.data.result);
                    window.open(url);
                }else{
                    var url = window.location.origin+window.location.pathname+'#/addAudio';
                    sessionStorage['robotAudio'] = JSON.stringify(item);
                    window.open(url);
                }
            })
        }


    //新增歌曲
    $scope.addAudio = function(){
        var url = window.location.origin+window.location.pathname+'#/addAudio';
        sessionStorage['robotAudio'] = 0;
        window.open(url);
    }

/*******************************************模块四：讲故事的相关*********************************************************************/

    var currentStoryPage = 1,
        storySearch = {},
        storyChange = true;   //查询条件是否更改
        function getFirstStory(){
            //是否是第一次查看的状态
            $scope.tabs[3].firstView = false;
            getStoryList();
            console.log('第一次讲故事');
        }

        //正式获取列表的数据
        function getStoryList(){
            var storyParam = {
                id:$('#story_id').val(),
                storyName:$('#story_title').val(),
                endTime:$('#story_date2').val(),
                startTime:$('#story_date1').val(),
                deleteStatus:$('#story_status option:checked').val()
            };
            if(compareStory(storyParam,storySearch)){
                storyChange = false;
            }else{
                //条件改变
                currentStoryPage = 1;
                storySearch = JSON.parse(JSON.stringify(storyParam));
                storyChange = true;
            }
            storySearch.pageNo = currentStoryPage;
            storySearch.pageSize = 10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/story/selectStory',
                params: storySearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(storyChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createStoryPage(10,20,data.result.totalResult);
                    }
                    $scope.storyList = data.result.entity;
                    console.log($scope.storyList);
                }
            })
        }

        //点击查询按钮
        $scope.storySelectAll = function(){
            getStoryList();
        }

        //判断查询条件有没有改变
        function compareStory(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.endTime != obj2.endTime  || obj1.deleteStatus != obj2.deleteStatus|| obj1.storyName != obj2.storyName
                || obj1.startTime != obj2.startTime){
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createStoryPage(pageSize, buttons, total) {
            $("#storyPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentStoryPage = (pageIndex+1);  //记录此时的页数
                    getStoryList(storySearch);
                }
            });
        }

        //显示隐藏操作
        $scope.storyChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    storyShowOrHide(0, id, $scope);
                }else{
                    storyShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        function storyShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.audioList[$scope.$index]));
            if(param.createTime){
                delete  param.createTime;
            }
            if(param.updateTime){
                delete param.updateTime;
            }
            param.deleteStatus = status;
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/song/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                    if($scope.audioList[$scope.$index].deleteStatus == 0){
                        $scope.audioList[$scope.$index].deleteStatus = 1;
                    }else{
                        $scope.audioList[$scope.$index].deleteStatus = 0;
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
        $scope.storyUpdate = function(item){
            //var url = window.location.origin+window.location.pathname+'#/addStory';
            //sessionStorage['robotStory'] = JSON.stringify(item);
            //window.open(url);
            getStoryById(item);
        }
        function getStoryById(item){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/story/selectStoryDetail',
                params:{id:item.id},
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    var url = window.location.origin+window.location.pathname+'#/addStory';
                    sessionStorage['robotStory'] = JSON.stringify(res.data.result);
                    window.open(url);
                }else{
                    var url = window.location.origin+window.location.pathname+'#/addStory';
                    sessionStorage['robotStory'] = JSON.stringify(item);
                    window.open(url);
                }
            })
        }


    //新增故事
    $scope.addStory = function(){
        var url = window.location.origin+window.location.pathname+'#/addStory';
        sessionStorage['robotStory'] = 0;
        window.open(url);
    }
/*******************************************模块五：游戏的相关*********************************************************************/
    var currentGamesPage = 1,
        gamesSearch = {},
        gamesChange = true;   //查询条件是否更改
        //获取分类
        //获取段子分类
            function getGamesType(){
                $http({
                    method: 'get',
                    url: window.reqUrl+'/management/game/category',
                    headers: {'authorization': token},
                }).then(function success(res) {
                    var data = res.data;
                    if(data.code == 0){
                        $scope.optionsGame = data.result;
                    }
                    getGamesList();
                })
            }
        function getFirstGames(){
            //是否是第一次查看的状态
            $scope.tabs[4].firstView = false;
            getGamesType();
            console.log('第一次游戏');
        }
        //正式获取列表的数据
        function getGamesList(){
            var gamesParam = {
                id:$('#game_id').val(),
                category:parseInt($('#game_type option:checked').val()) || '',
                deleteStatus:$('#game_status option:checked').val()
            };
            if(compareGames(gamesParam,gamesSearch)){
                gamesChange = false;
            }else{
                //条件改变
                currentGamesPage = 1;
                gamesSearch = JSON.parse(JSON.stringify(gamesParam));
                gamesChange = true;
            }
            gamesSearch.pageNo = currentGamesPage;
            gamesSearch.pageSize = 10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/game/selectGame',
                params: gamesSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(gamesChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createGamesPage(10,20,data.result.totalResult);
                    }
                    $scope.gamesList = data.result.entity;
                }
            })
        }


        //点击查询按钮
        $scope.gamesSelectAll = function(){
            getGamesList();
        }

        //判断查询条件有没有改变
        function compareGames(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.category != obj2.category  || obj1.deleteStatus != obj2.deleteStatus){
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createGamesPage(pageSize, buttons, total) {
            $("#gamesPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentGamesPage = (pageIndex+1);  //记录此时的页数
                    getGamesList(gamesSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.gamesChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    gamesShowOrHide(0, id, $scope);
                }else{
                    gamesShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }
        //获取对应的游戏类别id
        function getGameId(game){
               var typeId = '';
            $scope.optionsGame.forEach(function(item){
                if(item.label == game){
                    typeId = item.val;
                    return;
                }
            })
            return typeId;
        }

        function gamesShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.gamesList[$scope.$index]));
                var para = {
                    id:param.id,
                    category:getGameId(param.categoryLabel),
                    deleteStatus:status,
                    gameName:param.gameName,
                    gameUrl:param.gameUrl,
                    weight:param.weight
                };
                $http({
                    method: 'POST',
                    url: window.reqUrl+'/management/game/update',
                    data:para,
                    transformRequest: function (obj) {
                        var str = [];
                        for (var p in obj) {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    },
                    headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
                }).success(function (response) {
                    //成功提交
                    if (response.code == 0) {
                        layer.msg('操作成功!')
                        //返回
                        if($scope.gamesList[$scope.$index].deleteStatus == 0){
                            $scope.gamesList[$scope.$index].deleteStatus = 1;
                        }else{
                            $scope.gamesList[$scope.$index].deleteStatus = 0;
                        }
                    }else{
                        layer.msg(response.result);
                    }
                }).error(function (response) {
                    layer.msg(response.result);
                });

        }



        //点击修改之后的跳转
        $scope.gamesUpdate = function(item){
            //var url = window.location.origin+window.location.pathname+'#/addGame';
            //sessionStorage['robotGame'] = JSON.stringify(item);
            //window.open(url);
            getGameById(item);
        }

        function getGameById(item){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/game/selectGameDetail',
                params:{id:item.id},
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    var url = window.location.origin+window.location.pathname+'#/addGame';
                    sessionStorage['robotGame'] = JSON.stringify(res.data.result);
                    window.open(url);
                }else{
                    var url = window.location.origin+window.location.pathname+'#/addGame';
                    sessionStorage['robotGame'] = JSON.stringify(item);
                    window.open(url);
                }
            })
        }




        //新增游戏
    $scope.addGame = function(){
        var url = window.location.origin+window.location.pathname+'#/addGame';
        sessionStorage['robotGame'] = 0;
        window.open(url);
    }
/*******************************************模块六：段子的相关*********************************************************************/
        var currentJokesPage = 1,
            jokesSearch = {},
            jokesChange = true;   //查询条件是否更改
        //获取分类
        //获取段子分类
        function jokesType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/joke/category',
                //params: quesSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.options = data.result;
                    getJokesList();
                }
            })
        }
        function getFirstJokes(){
            //是否是第一次查看的状态
            $scope.tabs[5].firstView = false;
            jokesType();
            console.log('第一次段子');
        }
        //正式获取列表的数据
        function getJokesList(){
            var jokesParam = {
                id:$('#jokes_id').val(),
                category:$('#jokes_type option:checked').val(),
                deleteStatus:$('#jokes_status option:checked').val()
            };
            if(compareJokes(jokesParam,jokesSearch)){
                jokesChange = false;
            }else{
                //条件改变
                currentJokesPage = 1;
                jokesSearch = JSON.parse(JSON.stringify(jokesParam));
                jokesChange = true;
            }
            jokesSearch.pageNo = currentJokesPage;
            jokesSearch.pageSize = 10;
            $http({
                method: 'get',
                url: window.reqUrl+'/management/joke/selectJoke',
                params: jokesSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    if(jokesChange){
                        layer.msg('查询到'+data.result.totalResult+'条记录！');
                        //重置页数显示
                        createJokesPage(10,20,data.result.totalResult);
                    }
                    $scope.jokesList = data.result.entity;
                }
            })
        }

        //点击查询按钮
        $scope.jokesSelectAll = function(){
            getJokesList();
        }

        //判断查询条件有没有改变
        function compareJokes(obj1,obj2){
            var flag = true;
            if(obj1.id != obj2.id || obj1.category != obj2.category  || obj1.deleteStatus != obj2.deleteStatus){
                flag = false;
            }
            return flag;
        }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createJokesPage(pageSize, buttons, total) {
            $("#jokesPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentJokesPage = (pageIndex+1);  //记录此时的页数
                    getJokesList(jokesSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.jokeChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    jokesShowOrHide(0, id, $scope);
                }else{
                    jokesShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }


        function getJokeTypeId(text){
            var typeId = '';
            $scope.options.forEach(function(item){
                if(item.label == text){
                    typeId = item.val;
                    return;
                }
            })
            return typeId;
        }
        function jokesShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.jokesList[$scope.$index]));
            var para = {
                category:getJokeTypeId(param.categoryLabel),
                deleteStatus:status,
                jokeContent:param.jokeContent,
                jokeUrl:param.jokeUrl,
                weight:param.weight,
                id:param.id
            };
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/joke/update',
                data:para,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                    if($scope.jokesList[$scope.$index].deleteStatus == 0){
                        $scope.jokesList[$scope.$index].deleteStatus = 1;
                    }else{
                        $scope.jokesList[$scope.$index].deleteStatus = 0;
                    }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
        $scope.jokesUpdate = function(item){
            //var url = window.location.origin+window.location.pathname+'#/addJoke';
            //sessionStorage['robotJoke'] = JSON.stringify(item);
            //window.open(url);
            getJokeById(item);
        }


        function getJokeById(item){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/joke/selectJokeDetail',
                params:{id:item.id},
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    var url = window.location.origin+window.location.pathname+'#/addJoke';
                    sessionStorage['robotJoke'] = JSON.stringify(res.data.result);
                    window.open(url);
                }else{
                    var url = window.location.origin+window.location.pathname+'#/addJoke';
                    sessionStorage['robotJoke'] = JSON.stringify(item);
                    window.open(url);
                }
            })
        }






        //新增段子
    $scope.addJoke = function(){
        var url = window.location.origin+window.location.pathname+'#/addJoke';
        sessionStorage['robotJoke'] = 0;
        window.open(url);
    }
/*******************************************模块七：拼智商的相关*********************************************************************/

   //第一次切换到该tab的时候
    //初始化请求参数

    var currentQuesPage = 1,
        quesSearch = {},
        quesChange = true;   //查询条件是否更改



   //正式获取列表的数据
   function getQuesList(){
       var quesParam = {
           id:$('#ques_id').val(),
           startTime:$('#ques_date1').val(),
           endTime:$('#ques_date2').val(),
           deleteStatus:$('#ques_status option:checked').val()
       };
       if(compareQues(quesParam,quesSearch)){
           quesChange = false;
       }else{
           //条件改变
           currentQuesPage = 1;
           quesSearch = JSON.parse(JSON.stringify(quesParam));
           quesChange = true;
       }
       quesSearch.pageNo = currentQuesPage;
       quesSearch.pageSize = 10;
       $http({
           method: 'get',
           url: window.reqUrl+'/management/puzzle/selectPuzzle',
           params: quesSearch,
           headers: {'authorization': token},
       }).then(function success(res) {
           var data = res.data;
           if(data.code == 0){
               if(quesChange){
                   layer.msg('查询到'+data.result.totalResult+'条记录！');
                   //重置页数显示
                   createQuesPage(10,20,data.result.totalResult);
               }
               $scope.quesList = data.result.entity;
           }
       })
   }

        function getFirstQues(){
            //更改是否第一次查看的状态
            $scope.tabs[6].firstView = false;
            getQuesList();
            console.log('第一次段子');
        }

        //点击查询按钮
        $scope.quesSelectAll = function(){
            getQuesList();
        }

   //判断查询条件有没有改变
   function compareQues(obj1,obj2){
       console.log(obj1);
       console.log(obj2);
       var flag = true;
       if(obj1.id != obj2.id || obj1.startTime != obj2.startTime || obj1.endTime != obj2.endTime || obj1.deleteStatus != obj2.deleteStatus){
           flag = false;
       }
       return flag;
   }

        /**
         *
         * @param pageSize 每页的数据条数
         * @param buttons 外显多少个页数按钮
         * @param total   总共的数据条数
         */
        function createQuesPage(pageSize, buttons, total) {
            $("#quesPage").jBootstrapPage({
                pageSize : pageSize,
                total : total,
                maxPageButton:buttons,
                onPageClicked: function(obj, pageIndex) {
                    console.log('当前选择的页数'+(pageIndex+1));
                    currentQuesPage = (pageIndex+1);  //记录此时的页数
                    getQuesList(quesSearch);
                }
            });
        }

        //显示隐藏操作
        $scope.quesChange = function (status, id, $scope) {
            layer.confirm(status==1?'确定改成有效吗？':'确定改成无效吗?', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(status == 1){
                    quesShowOrHide(0, id, $scope);
                }else{
                    quesShowOrHide(1, id, $scope);
                }

            }, function(){

            });
        }

        function quesShowOrHide(status, id, $scope) {
            var param =JSON.parse(JSON.stringify($scope.quesList[$scope.$index]));
            if(param.createTime){
                delete  param.createTime;
            }
            if(param.updateTime){
                delete  param.updateTime;
            }
            param.deleteStatus = status;
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/puzzle/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('操作成功!')
                    //返回
                        if($scope.quesList[$scope.$index].deleteStatus == 0){
                            $scope.quesList[$scope.$index].deleteStatus = 1;
                        }else{
                            $scope.quesList[$scope.$index].deleteStatus = 0;
                        }
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });

        }



        //点击修改之后的跳转
    $scope.quesUpdate = function(item){
        var url = window.location.origin+window.location.pathname+'#/addQues';
        sessionStorage['robotQues'] = JSON.stringify(item);
        window.open(url);
    }


    //新增问题
    $scope.addQues = function(){
        var url = window.location.origin+window.location.pathname+'#/addQues';
        sessionStorage['robotQues'] = 0;
        window.open(url);
    }

       //点击查看大图
        $scope.showPs = function(link){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                //area: ['500px', '95%'],
                skin: 'layui-layer-nobg',
                content:'<img src='+link+'>'
            });
        }



        ////////////////////////////////////////////////////////////////////////
        //点击tab进行切换
        $scope.changeTab = function(id){
            if($scope.tabs[id].selected){
                return false;
            }
            $scope.tabs.forEach(function(item,index){
                if(index == id){

                    $scope.tabs[index].selected = true;
                    //记录下此时点击的tab缓存
                    console.log(item);

                    sessionStorage['nowTabId'] = index;
                    if(item.firstView){
                        //第一次进去

                        switch(index){
                            case 0:
                                getFirstImg();   //最开始的方法
                                break;
                            case 1:
                                getFirstMotion();
                                break;
                            case 2:
                                getFirstAudio();
                                break;
                            case 3:
                                getFirstStory();
                                break;
                            case 4:
                                getFirstGames();
                                break;
                            case 5:
                                getFirstJokes();
                                break;
                            //拼智商
                            case 6:
                                getFirstQues();
                                break;
                        }
                    }
                }else{
                    $scope.tabs[index].selected = false;
                }
            })
        }
        var nowIndex = parseInt(sessionStorage['nowTabId']) || 0;
        $scope.changeTab(nowIndex);





    }])



    // 新增修改美图
    .controller('imgCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        //标题界面
        var imgId = '',
            token = localStorage['token'];
        //获取类型数据
        function getImgType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/prettyPic/category',
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.options = data.result;
                    if($scope.data.categoryLabel){
                        $('#img_add_mold option[value="' + $scope.data.categoryLabel + '"]').attr('selected', 'selected');
                    }
                }
            })
        }
        if(sessionStorage['robotImg'] == 0){
            $('#showPageName').text('新增美图......O(∩_∩)O~~');
            $scope.msg = '新增';
            imgId = 0;
            $scope.data = {
                category:'',
                deleteStatus:0,
                picUrl:'',
                weight:0
            };
        }else{
            $('#showPageName').text('修改美图......O(∩_∩)O~~');
            $scope.msg = '修改';
            //imgId=  sessionStorage['imgId'] || 0;
            $scope.showBack = true;
            $scope.data = JSON.parse(sessionStorage['robotImg']);
            console.log($scope.data);
            imgId = $scope.data.id;
            //从缓存中拿到数据:显示有效性一栏的数据
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
        }
        getImgType();


        //显示/删减图片
        $scope.showPhotos = function(link){
            if(link){
                //第一张图片的删除
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.picUrl = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }

        // 设置数据
        //点击保存
        $scope.imgPost = function(){
          //获取此时的数据
            $scope.data.category = parseInt($('#img_add_mold option:checked').attr('tip') || '');
            $scope.data.deleteStatus = $('input:radio[name=addType]:checked').val();
            if(!$scope.data.picUrl){
                layer.msg('请上传图片!');
            }else{
                //进行数据的提交
                if(imgId == 0){
                    submitPic();
                }else{
                    modifyPic();
                }
            }
        }

        //新增美图
        function  submitPic(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/prettyPic/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    $timeout(function(){
                       $scope.data = {
                           category:'',
                           deleteStatus:0,
                           picUrl:'',
                           weight:0
                       };
                    },500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改美图
        function modifyPic(){
             var param = {
                 id:$scope.data.id,
                 category:$scope.data.category,
                 deleteStatus:$scope.data.deleteStatus,
                 picUrl:$scope.data.picUrl,
                 weight:$scope.data.weight
             };
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/prettyPic/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    setTimeout(function(){
                       window.close();
                    },1500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //上传图片 upload_adImg_icon
        $('#upload_adImg_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.picUrl = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        //点击取消
        $scope.imgCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                if(imgId!=0){
                    window.close();
                }else{
                    var url = window.location.origin+window.location.pathname+'#/robot';
                    location.href = url;
                    layer.msg('返回成功');
                }
            }, function(){

            });
        }
    }])

    // 新增表情包
    .controller('motionCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        //标题界面
        var motionId = '',
            token = localStorage['token'];
        //获取类型数据
        function getMotionType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/picPackage/category',
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.options = data.result;
                }
            })
        }
        if(sessionStorage['robotMotion'] == 0){
            $('#showPageName').text('新增表情......O(∩_∩)O~~');
            $scope.msg = '新增';
            motionId = 0;
            $scope.data = {
                category:'',
                deleteStatus:0,
                picUrl:'',
                weight:0
            };
        }else{
            $('#showPageName').text('修改表情......O(∩_∩)O~~');
            $scope.msg = '修改';
            $scope.showBack = true;
            $scope.data = JSON.parse(sessionStorage['robotMotion']);
            console.log($scope.data);
            motionId = $scope.data.id;
            //从缓存中拿到数据:显示有效性一栏的数据
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
            $timeout(function(){
                if($scope.data.categoryLabel){
                    $('#motion_add_mold option[tip="' + $scope.data.categoryLabel + '"]').attr('selected', 'selected');
                }
            },500)
        }
        getMotionType();


        //显示/删减图片
        $scope.showPhotos = function(link){
            if(link){
                //第一张图片的删除
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.picUrl = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }

        // 设置数据
        //$('#img_add_mold option[value="' + $scope.dataAll.mold + '"]').attr('selected', 'selected'); //设置分类
        //点击保存
        $scope.motionPost = function(){
            //获取此时的数据
            $scope.data.category = parseInt($('#motion_add_mold option:checked').val() || '');
            $scope.data.deleteStatus = $('input:radio[name=addType]:checked').val();
            if(!$scope.data.picUrl){
                layer.msg('请上传图片!');
            }else{
                //进行数据的提交
                if(motionId == 0){
                    submitMotion();
                }else{
                    modifyMotion();
                }
            }
        }

        //新增表情
        function  submitMotion(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/picPackage/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    $timeout(function(){
                        $scope.data = {
                            //category:$scope.options[0].val,
                            category:'',
                            deleteStatus:0,
                            picUrl:'',
                            weight:0
                        };
                    },1500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改表情
        function modifyMotion(){
            var param = {
                id:$scope.data.id,
                category:parseInt($('#motion_add_mold option:checked').val()),
                deleteStatus:$scope.data.deleteStatus,
                picUrl:$scope.data.picUrl,
                weight:$scope.data.weight
            };
            console.log(param);
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/picPackage/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    setTimeout(function(){
                        window.close();
                    },1500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //上传图片 upload_adImg_icon
        $('#upload_motion_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.picUrl = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        //点击取消
        $scope.motionCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close();
            }, function(){

            });
        }
    }])

    //新增唱歌系列
    .controller('audioCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        var audioId = '',
            token = localStorage['token'];
        $scope.data = {};
        if(sessionStorage['robotAudio'] == 0){
            audioId = 0;
            //属于新增
            $scope.msg = '新增';
            $('#showPageName').text('新增歌曲......O(∩_∩)O~~');
            $scope.data = {
                songName:'', //歌曲名称
                songDuration:'', //时长
                deleteStatus:'',
                songUrl:'', //故事链接
                weight:0
            };
        }else{
            //属于修改
            $scope.msg = '修改';
            $scope.data= JSON.parse(sessionStorage['robotAudio']);
            audioId = $scope.data.id;
            console.log($scope.data);
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
            $('#showPageName').text('修改歌曲......O(∩_∩)O~~');
        }

        //添加歌曲信息
        $scope.audioPost = function(){
            if(!$scope.data.songUrl){
                layer.msg('请上传音频！');
                return false;
            }
            //获取分类和显示
            $scope.data.deleteStatus = parseInt($('input:radio[name=addType]:checked').val());
            if(audioId == 0){
                submitAudio();
                console.log($scope.data);
            }else{
                if($scope.data.createTime){
                    delete $scope.data.createTime;
                }
                if($scope.data.updateTime){
                    delete $scope.data.updateTime;
                }
                modifyAudio();
            }
        }
        //删除音频
        $scope.delAudioFile = function(){
            layer.confirm('确定删除音频吗？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                $timeout(function(){
                    $scope.data.songUrl = '';
                },0);
                layer.msg('删除成功', {icon: 1});
            }, function(){

            });
        }
        //新增歌曲接口
        function submitAudio(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/song/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('新增成功!')
                    //重置数据
                   $timeout(function(){
                       $scope.data = {
                           songName:'', //歌曲名称
                           songDuration:'', //时长
                           deleteStatus:'',
                           songUrl:'', //故事链接
                           weight:0
                       };
                   },1000)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改段子接口
        function modifyAudio(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/song/update',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('修改成功!')
                    //返回
                    setTimeout(function(){
                        window.close();
                    },2000);
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }

        //上传音频
        $('#audio_add_audio').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            $('#audio_col_file span.course').text('正在上传...');
            client.multipartUpload(storeAs, file).then(function (result) {
                var audioUrl = result.res.requestUrls[0].split('?');
                if (audioUrl.length > 0) {
                    $('.delAudioFile').show();
                    layer.msg('上传成功!');
                }
                layer.msg('上传成功!');
                $timeout(function(){
                    $scope.data.songUrl = audioUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });


        //点击取消之后的操作
        $scope.audioCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close();
            }, function(){

            });
        }




        //返回
        $scope.cancel = function(){
            window.close();
        }
    }])
    //新增故事 系列
    .controller('storyCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        var storyId = '',
            token = localStorage['token'];
        $scope.data = {};
        if(sessionStorage['robotStory'] == 0){
            storyId = 0;
            //属于新增
            $scope.msg = '新增';
            $('#showPageName').text('新增故事......O(∩_∩)O~~');
            $scope.data = {
                storyName:'', //故事名称
                storyDuration:'', //时长
                deleteStatus:'',
                storyUrl:'', //故事链接
                weight:0
            };
        }else{
            //属于修改
            $scope.msg = '修改';
            $scope.data = JSON.parse(sessionStorage['robotStory']);
            storyId = $scope.data.id;
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
            $('#showPageName').text('修改故事......O(∩_∩)O~~');
        }

        //添加故事信息
        $scope.storyPost = function(){
            if(!$scope.data.storyUrl){
                layer.msg('请上传音频！');
                return false;
            }
            //获取分类和显示
            $scope.data.deleteStatus = parseInt($('input:radio[name=addType]:checked').val());
            if(storyId == 0){
                submitStory();
            }else{
                modifyStory();
            }
        }
        //删除音频
        $scope.delAudioFile = function(){
            layer.confirm('确定删除音频吗？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                //判断是删的哪张
                $timeout(function(){
                    $scope.data.storyUrl = '';
                },0);
                layer.msg('删除成功', {icon: 1});
            }, function(){

            });
        }
        //新增故事接口
        function submitStory(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/story/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('新增成功!')
                    //重置数据
                    $timeout(function(){
                        $scope.data = {
                            storyName:'', //故事名称
                            storyDuration:'', //时长
                            deleteStatus:'',
                            storyUrl:'', //故事链接
                            weight:0
                        };
                    },1000)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改段子接口
        function modifyStory(){
            if($scope.data.createTime){
                delete  $scope.data.createTime;
            }
            if($scope.data.updateTime){
                delete  $scope.data.updateTime;
            }
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/story/update',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('修改成功!')
                    //返回
                    setTimeout(function(){
                        window.close();
                    },2000);
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }

        //上传音频
        $('#story_add_audio').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            $('#audio_col_file span.course').text('正在上传...');
            client.multipartUpload(storeAs, file).then(function (result) {
                var audioUrl = result.res.requestUrls[0].split('?');
                if (audioUrl.length > 0) {
                    $('.delAudioFile').show();
                    layer.msg('上传成功!');
                }
                layer.msg('上传成功!');
                $timeout(function(){
                    $scope.data.storyUrl = audioUrl[0].replace('http', 'https');
                },0);
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });


        //点击取消之后的操作
        $scope.storyCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close();
            }, function(){

            });
        }




        //返回
        $scope.cancel = function(){
            window.close();
        }
    }])
    //新增游戏 系列
    .controller('gameCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        //标题界面
        var gameId = '',
            token = localStorage['token'];
        //获取类型数据
        function getGamesType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/game/category',
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.options = data.result;
                    $timeout(function(){
                        if($scope.data.categoryLabel){
                            $('#game_type option[tip="' + $scope.data.categoryLabel + '"]').attr('selected', 'selected');
                        }
                    },500)
                }
            })
        }
        if(sessionStorage['robotGame'] == 0){
            $('#showPageName').text('新增游戏......O(∩_∩)O~~');
            $scope.msg = '新增';
            gameId = 0;
            $scope.data = {
                category:'',
                deleteStatus:0,
                gameUrl:'',
                gameName:'',
                weight:0
            };
        }else{
            $('#showPageName').text('修改美图......O(∩_∩)O~~');
            $scope.msg = '修改';
            $scope.data = JSON.parse(sessionStorage['robotGame']);
            console.log($scope.data);
            gameId = $scope.data.id;
            //从缓存中拿到数据:显示有效性一栏的数据
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
        }
        getGamesType();



        // 设置数据
        //点击保存
        $scope.gamePost = function(){
            //获取此时的数据
            $scope.data.category = parseInt($('#game_type option:checked').val());
            $scope.data.deleteStatus = $('input:radio[name=addType]:checked').val();
                //进行数据的提交
                console.log($scope.data);
                if(gameId == 0){
                    submitGame();
                }else{
                    modifyGame();
                }
        }

        //新增游戏
        function  submitGame(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/game/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    $timeout(function(){
                        $scope.data = {
                            category:'',
                            deleteStatus:0,
                            gameName:'',
                            gameUrl:'',
                            weight:0
                        };
                    },500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改游戏
        function modifyGame(){
            var param = {
                id:$scope.data.id,
                category:$scope.data.category,
                deleteStatus:$scope.data.deleteStatus,
                gameName:$scope.data.gameName,
                gameUrl:$scope.data.gameUrl,
                weight:$scope.data.weight
            };
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/game/update',
                data:param,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('提交成功!');
                    setTimeout(function(){
                        window.close();
                    },1500)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }

        //点击取消
        $scope.gameCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close()
            }, function(){

            });
        }
    }])
    //新增段子系列
    .controller('jokeCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
        var jokeId = '',
            joke = {},
            token = localStorage['token'];
        $scope.data = {};
        //获取段子分类
        function jokesType(){
            $http({
                method: 'get',
                url: window.reqUrl+'/management/joke/category',
                //params: quesSearch,
                headers: {'authorization': token},
            }).then(function success(res) {
                var data = res.data;
                if(data.code == 0){
                    $scope.options = data.result;
                }
                if(sessionStorage['robotJoke'] == 0){
                    jokeId = 0;
                    //属于新增
                    $scope.msg = '新增';
                    $('#showPageName').text('新增段子......O(∩_∩)O~~');
                    $scope.data = {
                        category:'',
                        deleteStatus:'',
                        jokeContent:'',
                        jokeUrl:'',
                        weight:0
                    };
                }else{
                    //属于修改
                    $scope.msg = '修改';
                    $('#showPageName').text('修改段子......O(∩_∩)O~~');
                    $scope.data = joke = JSON.parse(sessionStorage['robotJoke']);
                    console.log($scope.data);
                    jokeId = joke.id;
                    //设置有效无效
                    $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
                    $timeout(function(){
                        $('#jokes_add_mold option[tip="' + $scope.data.categoryLabel + '"]').attr('selected', 'selected');
                    },500)
                }
            })
        }
        jokesType();

        function getTypeId(text){
            var type = '';
            $scope.options.forEach(function(item,index){
               if(item.label == text){
                   type = item.val;
                   return;
               }
            })
            return type;
        }




        //添加段子信息
        $scope.jokePost = function(){
             //获取分类和显示
            $scope.data.category = parseInt($('#jokes_add_mold option:checked').val());
            $scope.data.deleteStatus = parseInt($('input:radio[name=addType]:checked').val());
            if(jokeId == 0){
                submitJoke();
            }else{
                //处理提交的数据
                if($scope.data.createTime){
                    delete $scope.data.createTime;
                }
                if($scope.data.categoryLabel){
                    delete $scope.data.categoryLabel;
                }
                modifyJoke();
            }
        }
        //新增段子接口
        function submitJoke(){
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/joke/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('新增成功!')
                    //重置数据
                   $timeout(function(){
                       $scope.data = {
                           category:'',
                           deleteStatus:'',
                           jokeContent:'',
                           jokeUrl:'',
                           weight:0
                       };
                   },1000)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改段子接口
        function modifyJoke(){
            if($scope.data.createTime){
                delete  $scope.data.createTime;
            }
            if($scope.data.updateTime){
                delete  $scope.data.updateTime;
            }
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/joke/update',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('修改成功!')
                    //返回
                    setTimeout(function(){
                        window.close();
                    },2000);
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }

        //上传图图片
        $('#upload_joke_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.jokeUrl = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $scope.showPhotos = function(link){
            if(link){
                //第一张图片的删除
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        $scope.data.jokeUrl = '';
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){
                });
            }
        }


        //点击取消之后的操作
        $scope.jokeCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close();
            }, function(){

            });
        }


        //返回
        $scope.cancel = function(){
            window.close();
        }
    }])
    //新增智商问题系列
    .controller('quesCtrl',['$scope','$http','$timeout',function($scope,$http,$timeout){
      //标题处理
        var quesId = '',

            token = localStorage['token'];
        $scope.data = {};
        if(sessionStorage['robotQues'] == 0){
            //新增
            quesId = 0;
            $scope.msg = '新增';
            $('#showPageName').text('新增智商问题......O(∩_∩)O~~');
            $scope.data = {
                answer:'',
                answerPicUrl:'',
                deleteStatus:'', //0 显示 1 不显示
                question:'',
                questionPicUrl:'',
                weight:0
            };
        }else{
            $('#showPageName').text('修改智商问题......O(∩_∩)O~~');
            //修改
            $scope.data = JSON.parse(sessionStorage['robotQues']);
            quesId = $scope.data.id;
            if($scope.data.weight){
                $scope.data.weight = parseInt($scope.data.weight);
            }
            $("input[name='addType'][value='" + $scope.data.deleteStatus + "']").attr('checked', true);
            $scope.msg = '修改';
        }



        //点击返回
        $scope.cancel = function(){
            window.close();
        }

        //点击保存之后的操作
        $scope.quesPost = function(){
           //获取状态值
            $scope.data.deleteStatus = $('input:radio[name=addType]:checked').val();
            console.log($scope.data);
            if(!quesId){
                //提交
                submitContent();
            }else{
                //$scope.data.id = quesId;
                modifyContent();
            }

        }

        //图片上传
        $('#upload_ques_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.questionPicUrl = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });

        $('#upload_answer_icon').on('change', function (e) {
            var file = e.target.files[0];
            var endName = file.name.split('.')[1];
            var storeAs = Date.parse(new Date()) + '.' + endName;
            client.multipartUpload(storeAs, file).then(function (result) {
                var iconUrl = result.res.requestUrls[0].split('?');
                $timeout(function(){
                    $scope.data.answerPicUrl = iconUrl[0].replace('http', 'https');
                },0)
            }).catch(function (err) {
                console.log(err);
            });
            $(this).val('');
        });
        //点击图片看大图/删除图片
        $scope.showPhotos = function(link,type){
            if(link){
                //第一张图片的删除
                layer.confirm('确定删除图片吗？<br><img src="'+link+'" alt="">', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    //判断是删的哪张
                    $timeout(function(){
                        if(type == 'ques'){
                            $scope.data.questionPicUrl = '';
                        }else{
                            $scope.data.answerPicUrl = '';
                        }
                    },0);
                    layer.msg('删除成功', {icon: 1});
                }, function(){

                });
            }
        }

        //新增内容
        function submitContent(){

            $http({
                method: 'POST',
                url: window.reqUrl+'/management/puzzle/add',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('新增成功!')
                    //重置数据
                    $timeout(function(){
                        $scope.data = {
                            answer:'',
                            answerPicUrl:'',
                            deleteStatus:'', //0 显示 1 不显示
                            question:'',
                            questionPicUrl:'',
                            weight:0
                        };
                    },0)
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }
        //修改内容
        function modifyContent(){
            if($scope.data.createTime){
                delete  $scope.data.createTime;
            }
            if($scope.data.updateTime){
                delete  $scope.data.updateTime;
            }
            $http({
                method: 'POST',
                url: window.reqUrl+'/management/puzzle/update',
                data:$scope.data,
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded','authorization':token},
            }).success(function (response) {
                //成功提交
                if (response.code == 0) {
                    layer.msg('修改成功!')
                    //返回
                   setTimeout(function(){
                       window.close();
                   },2000);
                }else{
                    layer.msg(response.result);
                }
            }).error(function (response) {
                layer.msg(response.result);
            });
        }



        //点击取消之后的操作
        $scope.quesCancel = function(){
            layer.confirm('请确保提交成功，返回之后数据会清空，确定返回吗？', {
                btn: ['返回','继续'] //按钮
            }, function(){
                window.close();
            }, function(){

            });
        }

    }])

